How to pass arguments from terminal to a function
Solution 1
Your main function should be in the format:
int main ( int argc, char *argv[] )
argv is a pointer to your arguments. Note that the first argument is the name of your program.
Here is a lesson on command line arguments:
Solution 2
Course you can, main prototype is int main(int ac, char **av)
where ac is the number of arguments passed to the program and char** is an array of arrays containing the arguments passed to the program.
For example for your code :
int main(int ac, char **av)
{
void replace (av[1], av[2], av[3])
{
.......
}
}
If you launch your exec as : ./replace d DDD mytest.tx
, av[0] will be your program name, av[1] will be d
, av[2] DDD
and av[3] mytest.tx
Good luck !
Solution 3
All stand-alone proper C programs start their execution in main()
. That's just how the language works.
So what you need to do is call replace()
from main()
, after verifying and interpreting the arguments. The command-line arguments will be in the standard int argc, char *argv[]
parameters to main()
.
Solution 4
The thing you want to do is use main
's argument list.
You can use the following signature:
int main(int argc, char* argv[])
, where argv is a pointer to the argument list, passed from the command line.
Solution 5
Look up argc
and argv
.
argc is the number of arguments and argv is an array of pointers to your arguments.
so your code should look something like this:
void replace (char string_a[],char string_b[], char string_f[])
{
//...
}
int main(int argc, char *argv[])
{
if(argc < 4)
{
printf("Not enough arguments\n");
return 0;
}
replace(argv[1], argv[2], argv[3]);
}
Also remember that the first item in argv (argv[0]
) is the path of the executing program.
user1072706
Updated on September 26, 2020Comments
-
user1072706 over 3 years
Possible Duplicate:
Pass arguments into C program from command lineI am trying to pass three arguments from terminal into a function called replace. I would like to know if it is possible to do the following from terminal
% ./replace d DDD mytest.tx
I have looked online but can only find information on passing values directly to main() and not the function inside.
Edit: I have edited the main functions as following:
void replace(char* string_a, char* string_b, char* string_f) { } int main(int argc, char *argv[]) { if(argc < 4) { printf("Not enough arguments\n"); return 0; } replace(argv[1],argv[2],argv[3]); }
-
Mike over 11 yearsWhy not pass them to
main()
then to the function from there? Why are you trying to by-pass sending them tomain()
?
-
-
Tomislav Dyulgerov over 11 yearsActually av[0] will be the name of the program as Lews Therin has correctly pointed out.
-
Simon MILHAU over 11 yearsYep mistaken this =S Edited !
-
user1072706 over 11 yearsThanks for the explanation. No, I am not trying to bypass main; my goal is simply to call replace from terminal.