Reputation: 39
Ok I am creating a program that allows user input in any order. The term -1 or -2 is used to indicate an operating mode. while the argument -c always precedes a filename. Here is the loop I have written to allow these to be entered in any order the user wishes.
int main(int argc, char *argv[])
{
string qcolors_name;
string inputFileName;
pmode_t mode = run_process2;
// perform command line argument checking
if(argc < 2){
cerr << "Not enough arguments" << endl;
return 0;
}
for(int i = 1; i < argc - 1; i++){
if(argv[i] == "-1"){
mode = run_process1;
cout << "Mode 1" << endl;
}else if(argv[i] == "-2"){
mode = run_process2;
}else if(argv[i] == "-c"){
qcolors_name = argv[i+1];
cout << qcolors_name << endl;
i++;
}else if(argc-1 == i){
break;
}else{
cout << argv[i] <<endl;
cerr << "arguments error"<<endl;;
return 0;
}
}
However the program seems to always dump out to the arguments error message even though it outputs that argv[i] is = -1. This is one of the things I have tested for though and should never have reached this case. Im sure its something syntax wise that I am doing wrong.
EDIT
Here is an imput with a sample error output.
USER> ./colorfun -1 -c qc_bw.txt mountains.ppm <- 9:46PM
-1
arguments error
Upvotes: 0
Views: 2403
Reputation: 1146
In C++ you have to convert the arguments to std::string first, then you can compare them using the == operator, like this:
int main(int argc, char* argv[]) {
for (int i = 1; i < argc; i++) {
if (std::string(argv[i]) == "-a") {
std::cout << "You passed parameter -a" << std::endl;
} else if (std::string(argv[i]) == "-b") {
std::cout << "You passed parameter -b" << std::endl;
}
}
return 0;
}
Upvotes: 0
Reputation: 17455
It's C, you can't compare strings with just str1 == "smth". Use strcmp()
instead.
More detailed explanations: operator ==
in C compares integral entities: numbers, pointers, etc. "smth"
is essentially a pointer to memory area in constant segment of your program. That's why code like
const char* a = "abc";
const char* b = "abc";
assert(a == b);
may give true, both a & b may point to a single memory location. But this expression never compares letters "a", "b", "c" from a
and b
, it compares just pointers. Likewise in Java you have to use str1.equals(str2)
because Java operator == also compares integral entities (numbers, characters and "pointers to Objects"). In opposite in C++, Python and other programming languages with operator overloading, ==
for two strings usually leads to character by character comparison.
Upvotes: 2