I am new to programing. I am sure I am missing something simple. I just want take my switch and check if it's used or not. However, the else statement keeps being used. What am I missing?
1 2 3 4 5 6 7 8 9 10
#include <iostream>
int main(int argc, constchar **argv)
{
if (*argv == "-t")
std::cout<<"This is just a test!\n";
else
std::cout<<"Unknown command.\n";
return 0;
}
You cannot compare C strings (i.e. null-terminated char arrays) using operator==.
So just convert the argument into a real string beforehand:
1 2
std::string arg=argv[1];
if (arg=="-t")...
This requires the <string> header to be included.
Also note that the first argument is the program name - so the actual argument you're looking for is the second entry in argv.
That worked. However, when I didn't use a switch I got an error. So I modified it a tad so it didn't throw an error. However, it's not liking my while statement. Since Null is not making it happy what else can I use?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
int main(int argc, constchar **argv)
{
std::cout<<"Test of running command line parsing.\n\n";
std::string arg=argv[1];
while (arg != NULL)
{
if(arg == "-h")
std::cout<<"This is a demo help file.\n";
else
std::cout<<"Unknown command.\n";
}
return 0;
}
#include <iostream>
/* Use a function to print the full help message
Pass the arguments to it so you can use the program name, etc... */
void Help(int argc, constchar **argv) {
// std::cout is capable of quasi-multi-line statements, like so:
std::cout << "Usage: " << argv[0] << "[options]\n""Test of command-line argument parsing\n""\nOptions:\n""-h\tPrint this message and exit""\n";
}
int main(int argc, constchar **argv) {
std::cout << "CommandLine Argument Parsing Test\n\n";
if (argc > 1) {
std::string arg1 = argv[1];
if (arg1 == "-h")
Help(argc, argv); // Print Usage & Help info
return 0; // return to terminal after help msg, 0 for no errors
else {
// Use the error stream for error messages when possible...
std::cerr << "Error: Invalid switch '" << argv[1] << "'\n";
/* Tell the user exactly what went wrong and how to fix it ...
i.e. how to use the program correctly. */
Help(argc, argv);
return 1; // Return to terminal with error status 1 after an error
}
}
return 0; // return 0 for no errors
}