When running this code: ./a.out 5 + 5 i am supposed to get 10. but instead i get Unkown operator. does anyone know why this may be happening?
#include <iostream>
#include <string>
int main(int argc, char *argv[]){
if (argv[2]=="+"){
std::cout << std::stoi(argv[1])+std::stoi(argv[3]) << "\n";
}
else if (argv[2]=="-"){
std::cout << std::stoi(argv[1])-std::stoi(argv[3]) << "\n";
}
else{
std::cout << "Unkown operator." << "\n";
}
return 0;
}
>Solution :
This line is comparing pointer values, and not the strings data they point to…
if (argv[2]=="+"){
Either use strcmp:
if (strcmp(argv[2], "+") == 0){
}
Or something along these lines:
if (std::string(argv[2]) == "+"){
}