I'm a beginner to C++ and I'm trying to use if statements in a basic program to find out what command-line arguments were passed with the program. I have this:
#include <iostream>
#include <cstring>
usingnamespace std;
//void basicHelp();
//void detailedHelp();
int main(int argc, char** argv)
{
if (argc < 2)
{
//cout << "\n\nPlease enter a valid option. Usage of this tool is as follows:";
//basicHelp();
cout << "\nYou used no parameters.\n";
return 0;
}
if (argv[1] == (char*)"-h")
{
if (argv[2] == (char*)"-m")
{
//detailedHelp();
cout << "\nYou used the parameters -h and -m.\n";
return 0;
}
//basicHelp();
cout << "\nYou only used the parameter -h.\n";
return 0;
}
return 0;
}
All looked fine to me. The point was that if there were no additional arguments passed, "You used no parameters" would appear, and the other messages would appear if I used "-h", or if I used both "-h" and "-m" (in that order). But no, I get this:
1 2 3 4 5 6
main@bennun-ubuntu:~/Documents$ ./blah
You used no parameters.
main@bennun-ubuntu:~/Documents$ ./blah -h
main@bennun-ubuntu:~/Documents$ ./blah -h -m
main@bennun-ubuntu:~/Documents$
It doesn't see the other two parameters as "-h" and "-m". How can I make it do this? Is it a problem involving typecasting or something? I'm utterly confused.
Don't use type casting unless you know exactly what you are doing. It looks like you have used the cast here to get rid of a warning. The compiler tried to tell you something was wrong but you didn't listen. The problem is that you can't compare c strings with ==, because that will just compare the pointers. To compare two c strings you use std::strcmp instead.
Thanks very much for your reply. As I'm such a noob at C++, I was using typecasting so that I could make a comparison between two variables of the same type, but I didn't realise it was just comparing the pointers! I had no idea of strcmp's existence, and it has solved the problem. Thanks very much.
Here's the working code (working as far as I want it to currently) for anybody who's interested:
#include <iostream>
#include <cstring>
usingnamespace std;
//void basicHelp();
//void detailedHelp();
int main(int argc, char** argv)
{
if (argc < 2)
{
//cout << "\n\nPlease enter a valid option. Usage of this tool is as follows:";
//basicHelp();
cout << "\nYou used no parameters.\n";
return 0;
}
if (strcmp(argv[1],"-h") == 0)
{
if (argc >= 3)
{
if (strcmp(argv[2],"-m") == 0)
{
cout << "\nYou used -h and -m.\n";
return 0;
}
}
cout << "\nYou only used -h.\n";
}
return 0;
}
Aramil of Elixia: Do you know what a terminal is? Terminals use a command-line interface so it makes very much sense to be able to pass command-line arguments from it.