I have a program that reads hard-coded file-path and I want to make it read file-path from command line instead. For that purpose I changed the code like this:
#include <iostream> int main(char *argv[]) { ... }
but, argv[1]
variable exposed this way seems to be of type pointer, and I need it as a string. What should I do to convert this command line argument to string?
The length of this array is argc. Argument 0 is the path and name of the current program being run. Argument 1 and 2 in this case are the two command line parameters we passed in. Command line arguments are always passed as strings, even if the value provided is numeric in nature.
Each argument on the command line is separated by one or more spaces, and the operating system places each argument directly into its own null-terminated string. The second parameter passed to main() is an array of pointers to the character strings containing each argument (char *argv[]).
Python has a built-in function str() which converts the passed argument into a string format. The str() function returns a string version of an object. The object can be int , char , or a string .
Argc and argv Argv looks weird, but what it is is an array of C-style strings. Sometimes you see it declared as "char *argv[]," which is equivalent to the above. Element argv[i] will be a c style string containing the i-th command line argument. These are defined from 0 through argc-1.
It's already an array of C-style strings:
#include <iostream> #include <string> #include <vector> int main(int argc, char *argv[]) // Don't forget first integral argument 'argc' { std::string current_exec_name = argv[0]; // Name of the current exec program std::vector<std::string> all_args; if (argc > 1) { all_args.assign(argv + 1, argv + argc); } }
Argument argc
is count of arguments plus the current exec file.
You can create an std::string
#include <string> #include <vector> int main(int argc, char *argv[]) { // check if there is more than one argument and use the second one // (the first argument is the executable) if (argc > 1) { std::string arg1(argv[1]); // do stuff with arg1 } // Or, copy all arguments into a container of strings std::vector<std::string> allArgs(argv, argv + argc); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With