tags:

views:

96

answers:

4

i'm newby to C++.

Small code as follows:

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

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

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:

function main() ..

az

i get :

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 :

ax

and i also get same results.

Now if instead of int i use short and running the program.

function main() ..

az

i get:

a 0

ps: sizeof(int) = 4

sizeof(short) = 2

i am using 64 bit machine

+1  A: 

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.

Mike DeSimone
+4  A: 

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.

Dennis Zickefoose
+1 for checking stream state with cin.fail()
cschol
A: 

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
JProgrammer
A: 

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:

http://stackoverflow.com/questions/2407771/c-character-to-int/2411471#2411471

Baltasarq