Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert command line argument to string

Tags:

c++

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?

like image 923
theta Avatar asked Mar 11 '13 17:03

theta


People also ask

Are command line arguments strings C++?

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.

Are command line arguments string?

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[]).

How do you convert an argument to a string in Python?

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 .

Is argv 1 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.


2 Answers

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.

like image 191
masoud Avatar answered Oct 19 '22 04:10

masoud


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); } 
like image 30
juanchopanza Avatar answered Oct 19 '22 06:10

juanchopanza