cin erratic behaviour

我只是一个虾纸丫 提交于 2019-12-23 12:44:48

问题


I'm a newbie to C++. Small code sample follows:

int main(int argc, char* argv[]) {    

    char ch1;
    int int1;

    cin >> ch1;
    cin >> int1;

    cout << ch1 << '\n';
    cout << int1 << '\n';

    return 0;
}

When I run the program and input the following:

az

I get as output:

a 32767

I understand the 'a' but why the integer value of 32767? I just want to test and see what happen if instead of a numeric value assigned to int1 i used a 'z'.

I try inputting:

ax

...and I also get same results.

Now if instead of int int1 I use short int1 and run the program with input:

az

I get the output:

a 0

P.S.

sizeof(int) = 4
sizeof(short) = 2

I am using a 64-bit machine.


回答1:


When an input stream fails to read valid data, it doesn't change the value you passed it. 'z' is not a valid number, so int1 is being left unchanged. int1 wasn't initialized, so it happened to have the value of 32767. Check the value of cin.fail() or cin.good() after reading your data to make sure that everything worked the way you expect it to.




回答2:


cin >> int1; means "read an integer and put it in int1." So you feed it z, which is not a valid character in an integer, and it simply aborts the read and leaves whatever in int1.

Test this by initializing int1 to something and seeing what happens.




回答3:


The c++ cin stream is doing input validation for the program.

When streaming from cin into an int cin will only accept valid number didgits, -0123456789, and also only values between INT_MIN and INT_MAX.

If the numerical value for z (122) is required I would recommend using the c getchar function rather than the cin stream.

int main(int argc, char* argv[]) {

    cout << "function main() .." << '\n';

    char ch1 = getchar();
    int int1 = getchar();
    cout << ch1 << '\n';
    cout << int1 << '\n';

    return 0;

}

When az is input this will output

a
122



回答4:


Using cin directly is, personally, i.e., for me, a bad idea for reading data in non-trivial programs. I suggest you read another answer I gave for a similar question:

C++ character to int



来源:https://stackoverflow.com/questions/2451902/cin-erratic-behaviour

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!