'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!!";
Solution 1:[1]
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;
}
Other alternative is to do the opposite. That is, convert the std::string to int(if possible) and then perform the comparison.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Anoop Rana |
