Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

If statement on args giving odd outputs

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]) == "+"){
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading