简体   繁体   中英

what is wrong this static_cast piece of code?

I have this piece of code in c++

char a;
cin>>a; //I input 3 in this
a=static_cast<int>(a);
cout<<a+9<<endl;
a=static_cast<int>(4.2)
cout<<a;

Here is the result: 51 60 4

I was expecting static_cast(a) to produce 3. Can anyone tell me what I had misunderstood?

Let's go step by step.

char a;

Declares a character type . So far so good.

cin>>a; 

Inputs a character, or a textual representation of a number. If you enter '3' you will be entering the text version of 3. On ASCII systems, this will be 0x33 (or 51 decimal).

a=static_cast<int>(a);

By the way, the value in a before this statement is a number (the ASCII number of the character you entered).

You are telling the compiler to convert from the integral type char to an integral type int . (You are converting from a smaller capacity integer type to a larger capacity integer type). Next, you assign the int type into a char type. (You are converting from a larger capacity type, int , to a smaller capacity type, char .) Since they are both numeric, essentially nothing happens. The compiler may optimize this away.

cout<<a+9<<endl;  

You take the character in a and advance the encoding by 9. If you entered a character of 'A', you would now have 'J' (according to ASCII). Then you output the character and a newline.

a=static_cast<int>(4.2)  

Here, you are converting an floating point to an integer . The floating point gets truncated to 4. Next, the value 4 (0x04) gets truncated in length to fit into a char type and assigned to the variable a .

cout<<a;

This line outputs the character \\x04 . In ASCII, this is a non-printable character, EOT .

What you may want is conversion from string to integer or integer to string.

Remember that 4 != '4' on most text encoding systems.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM