Home > Blockchain >  Can we have a condition to compare int and string data type?
Can we have a condition to compare int and string data type?

Time:03-27

How can i make a condition to compare int and string?

int number; string guess;

if (guess!=number){ cout <<"You lose"; else cout<<"You win!!";

CodePudding user response:

One option would be to use std::to_string to convert the int to a std::string and then perform the comparison as shown below:

    int number = 5; std::string guess = "5";
//----------vvvvvvvvv------------------------->use std::to_string
    if(std::to_string(number)!= guess)
    {
        std::cout<<"not equal"<<std::endl;
    }
    else 
    {
        std::cout<<"equal"<<std::endl;
    }

Demo

Other alternative is to do the opposite. That is, convert the std::string to int(if possible) and then perform the comparison.

  • Related