blzn
blzn

Reputation: 75

Comparing int and char with cast

Why doesn't the function print "true" when '1' is input for both variables? How can I fix this?

int main() {
    int i;
    char c;
    cout << "Type int: ";
    cin  >> i;
    cout << "Type char: ";
    cin  >> c;
    if (i == (int)c)
        cout << "true" << endl;
    else 
        cout << "false" << endl;
}

Upvotes: 0

Views: 86

Answers (2)

AnT stands with Russia
AnT stands with Russia

Reputation: 320461

Even though char is an integer type, it is treated by the >> operator differently from other integer types.

  • For non-char integer recipient variable the >> operator treats the input as a representation of an integer value. The entire representation is consumed from the input, converted to integer and stored in the recepient variable. For example, if you enter 8 as the input, the recipient variable (say, an int) will receive integer value 8. If you enter 42 as the input, the recipient variable will receive integer value 42.

  • But for char recipient variable the >> operator treats the input as a mere character sequence. Only the first character of that sequence is consumed and immediately stored in the recipient variable. For example, if you enter 8 as the input, a char recipient variable will receive character '8', which corresponds to integer value of 56. If you enter 42 as the input, the recipient variable will receive character '4', which corresponds to integer value of 52.

That is what leads to the inequality in your case.

Upvotes: 2

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

Like other input stream objects, std::cin is designed to work differently when you read into different types.

For an int, it reads the numbers you write into the console and parses them into internal integer form. This is convenient: "formatted extraction" means we get a useful int right away and don't need to any conversions from string to number.

For a char, it reads the actual letter or digit or punctuation that you wrote into the console; it does not parse it. It simply stores that character. In this case, c is 49 because that is the ASCII value of '1'.

If you wanted to see whether the int contained 1 and the char contained '1' to match, then you can exploit the property of ASCII that all the digits are found in sequential order starting from 48, or '0':

if (`i` == `c`-'0')

However, if you do this, you should verify that:

  • Your platform uses ASCII;
  • c contains a digit ('0', '1', ..., '9').

Generally avoid these hacks if you can. There's usually another way to check your inputs.

Upvotes: 1

Related Questions