C++ character to int

前端 未结 5 1698
梦谈多话
梦谈多话 2020-12-11 16:36

what happens when you cin>> letter to int variable? I tried simple code to add 2 int numbers, first read them, than add them. But when I enter letter, it just fails and prin

5条回答
  •  -上瘾入骨i
    2020-12-11 17:02

    The issue is that when you read into an integer variable, using C++ streams, the input method expects characters that can make up a number, such as '+', '-', '0' ... '9'. Any character that is not in this set terminates the input and a number is created from these characters.

    To get the ASCII value of a character, you need to input the data into a char variable. Internally, it has the ASCII value (provided the program in not reading 16-bit chars or EBCDIC). If you want to see the ASCII value, you will need to output the char variable as an integer (generally requiring a cast before output).

    If reading an integer fails, your program needs to inform the User that the input was incorrect. The program may require the User to input the number again before the program can process the input data.

提交回复
热议问题