The line
string tab[argc];
is not valid ISO C++, because the length of the array must be a compile-time constant. Some compilers may support variable-length arrays as an extension, though.
However, it is possible to convert the C-style argv
strings to a std::vector
of std::string
. See this question for further information:
Convert command line argument to string
In your code, the line
if(argv[i]==' ') {
does not make sense, as you are comparing a pointer to a string with a character literal.
If you call your program like this
myprogramname red blue yellow
then the following will apply:
argc
will have the value 4
argv[0]
will point to a string containing myprogramname
argv[1]
will point to a string containing red
argv[2]
will point to a string containing blue
argv[3]
will point to a string containing yellow
argv[4]
will have the value NULL
Therefore, if you want to print yellow
, you can simply write
std::cout << argv[3] << '\n';
If you want to print the length of the string yellow
, you can simply write
std::cout << std::strlen( argv[3] ) << '\n';
Note that you must #include <cstring>
in order to use std::strlen
.
Alternatively, instead of using std::strlen
, you can first convert argv[3]
to a std::string
, before obtaining its length:
std::string str{ argv[3] };
std::cout << str.length() << '\n';
If you want to write to a file, such as to the std::fstream
with the name save
in your program, then you can replace std::cout
with save
in the code above. However, you will have to open the file first, before using it. Also, you may want to consider using std::ofstream
instead of std::fstream
, because you seem to only want to use the file for writing, not reading.