Cin erratic behavior

I am new to C ++. The following is a sample code:

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 enter the following:

ag

I get the output:

a 32767

I understand "a", but why is the integer value 32767? I just want to check and see what happens if, instead of the numeric value assigned to int1, I used 'z'.

I am trying to enter:

Oh

... and I get the same results.

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

ag

I get the output:

a 0

PS

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

I am using a 64-bit machine.

+4
source share
4 answers

When an input stream cannot read reliable data, it does not change the value that you passed to it. 'z' is not a valid number, so int1 remains unchanged. int1 was not initialized, so it had a value of 32767. Check the value of cin.fail () or cin.good () after reading your data to make sure everything works as you expect.

+4
source

cin >> int1; means "read an integer and put it in int1". So you feed it z , which is not a valid integer character, and it just interrupts the reading and leaves something in int1 .

Check this out by initializing int1 to something and seeing what happens.

+1
source

C ++ cin thread performs an input check for the program.

When streaming from cin to int cin only valid dogits, -0123456789, and only values ​​between INT_MIN and INT_MAX, will be accepted.

If a numeric value is required for z (122), I would recommend using the c getchar function, not 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 entered, it displays

 a 122 
0
source

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

C ++ character for int

0
source

Source: https://habr.com/ru/post/1304221/


All Articles