I am starting my c++ program from command line:
program input_file1 input_file2 output_file
where
int main( int argc, char *argv[] )
{
short indicator= 3;
char input_file1[4096], input_file2[4096], output_file[4096];
char *p_file = NULL;
while ( --argc > 0 ) {
switch (--indicator) {
case 2:
p_file = output_file;
break;
case 1:
p_file = input_file2;
break;
case 0:
p_file = input_file1;
break;
}
for (char *argument = argv[argc]; ; ++argument) {
if (*argument == '\0')
break;
else
*p_file++ = *argument;
}
*p_file = '\0';
}
std::cout << input_file1 << '\n';
std::cout << input_file2 << '\n';
std::cout << output_file << '\n';
}
But with the real arguments
program D:\\data\\file1.txt D:\\data\\file2.txt D:\\data\\file3.txt
in names of the files only the first letter D is stored...
Output:
D
D
D
Thanks for your help...
Ok, so here is the short version:
int main(int argc, char *argv[]) {
if (argc != 2) {
std::cout << "This program requires 1 argument!" << std::endl;
return 1;
}
std::string input_file(argv[1]);
std::cout << input_file << std::endl;
}
You should be able to take it from here.
This is a C problem, not a C++ one, but as it is tagged C++, i will suggest a C++ solution for your problem :
int main( int argc, char *argv[] ) {
std::vector<std::string> args(argv+1, argv+argc);
std::cout << args[0] << '\n' << args[1] << '\n' << args[2] << std::endl;
}
UPDATE using iterators on argv to fill the vector args (thanks Space_C0wb0y)
Rather than copying the arguments, just set the file names to point to the appropriate entry in argv.
int main(int argc, char *argv[]) {
char *input_file1, *input_file2, *output_file;
if (4 > argc)
{
std::cout << "Not enough parameters\n";
return -1;
}
input_file1 = argv[1];
input_file2 = argv[2];
output_file = argv[3];
std::cout << input_file1 << '\n';
std::cout << input_file2 << '\n';
std::cout << output_file << '\n';
}
the contents of argv will exist for as long as the program is running.
*p_file ++ = * argument;
This assigns the first character of arguement to the first character in p_file.
You need to use strcpy
, or declare some std::strings
instead of arrays of char
Your loop is all wrong. You are looping through characters, not the parameter array. You can do that like this:
for(auto arg = argv + 1; *arg; ++arg)
{
std::cout << (*arg) << '\n'; // *arg is a char*
}
This works because the arguments (if any) start at argv + 1
and because they are null terminated so that *arg
is nullptr
(converts to false
) at the end of the argument array.
Your arguments are obtained by dereferencing arg
using *arg
which is a char*
.
So you can do:
if(!std::strcmp(*arg, "--help"))
print_help_info();