문제

Why can't I test for the ASCII value I assign to symbol (250) in this code? It seems weird to be testing for -6 when that is not what I assigned to symbol.

#include <iostream>

using namespace std;

int main()
{

    char symbol = 250; // dot symbol

    int a = symbol;

    cout << symbol << endl; // Outputs dot symbol

    cout << a << endl; // Outputs -6

    if(symbol == 250)
        cout << "250 works";

    if(symbol == -6)
        cout << "-6 works"; // -6 test works

    return 0;
}
도움이 되었습니까?

해결책

char is signed on your platform. 250 is out of range for a signed character. You want:

if (symbol == static_cast<char>(250))

Otherwise symbol will be promoted to an integer. Alternatively, use unsigned char instead of char which may or may not be signed.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top