Hi,
I am new in the forum and i have a little question for you,
in my program i have to use a "value" that the user must be entered as
./"name of executable" -n "value"
How can i store and use that "value" value :p
Thanks
Printable View
Hi,
I am new in the forum and i have a little question for you,
in my program i have to use a "value" that the user must be entered as
./"name of executable" -n "value"
How can i store and use that "value" value :p
Thanks
FAQ > How do I... (Level 2) > Accessing command line parameters/arguments
FAQ > Prelude's Corner > Command line input
You need to parse the stuff passed to main():
argc is the number of elements in the argv array. Each element of argv is one command line token as the shell understands it: for POSIX shells, the first entry (argv[0]) is the part of the command line that called your program ("./executable"), each subsequent entry is one command line argument, separated by space, unless the space is escaped or within quotes. In your example call, argv[1] would be "-n" and argv[2] "value".Code:int main(int argc, char *argv[])
If the value is supposed to be a number, then you must parse its string representation, usually with strtol or atoi.
In addition, POSIX systems offer the program options functions (forgot the exact name), which parses standard UNIX command line options (e.g. sets flags with the - and -- stuff).
Along the same lines, Boost has the Program Options library, which does the same, but in a C++ way instead of C.
And argv[3] would be NULL.Quote:
argc is the number of elements in the argv array. Each element of argv is one command line token as the shell understands it: for POSIX shells, the first entry (argv[0]) is the part of the command line that called your program ("./executable"), each subsequent entry is one command line argument, separated by space, unless the space is escaped or within quotes. In your example call, argv[1] would be "-n" and argv[2] "value".
That's usually how it's written, but you might see it like this:Code:int main(int argc, char *argv[])
Code:int main(int argc, char **argv)
That's in C. :)Quote:
If the value is supposed to be a number, then you must parse its string representation, usually with strtol or atoi.
Indeed. Though I tend to parse numbers in C++ with atoi too, unless I'm allowed to use Boost and can use lexical_cast. Setting up a local stringstream is just too much hassle.