Reputation: 45
I'm trying to write a program that detects '-m' as an argument for a message and use double quotes between the message itself. Now I'm just trying to detect if the message starts with double quotes, but I get an unexpected behavior.
The main function:
int main(int argc, char *argv[]){
if (argc < 3){
std::cerr << "Error! Bad usage of parameters" << std::endl;
return 1;
}
for (int i = 1; i < argc - 1; i++){
std::string arg = argv[i];
std::string nextarg = argv[i+1];
if(arg == "-m"){
if(nextarg.empty() || nextarg[0] != '"'){
std::cout << "nextarg[0]: " << nextarg[0] << std::endl;
std::cout << "arg: " << arg << std::endl;
std::cerr << "Error, message must be on double quotes" << std::endl;
return 1;
}
else {
std::cout << "The code worked" << std::endl;
std::cout << nextarg << std::endl;
std::cout << arg << std::endl;
}
return 0;
}
else{
std::cerr << "The value is invalid." << std::endl;
return 1;
}
}
}
Now, the input I'm using is ./compiled -m "foo foo"
, and the expected output is:
The code worked
"foo foo"
-m
But the actual output is:
nextarg[0]: f
arg: -m
Error, message must be on double quotes
So, I see the problem is probably that my program doesn't detect the first double quotes. Also, if I use only one double quotes, the output makes an infinite loop of '>' asking me for an input, I don't want that behavior in my program.
By the way, I don't know why, but my program works if I use this input: ./compiled -m "\"foo foo\""
, so I think that must be a problem with the terminal itself, but I still don't know anything about that.
Upvotes: 1
Views: 312