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

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

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!!";

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

>Solution :

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.

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