C ++字符到int [英] C++ character to int
问题描述
当你把字母变成int变量时会发生什么?我试着简单的代码添加2个int数字,首先阅读它们,而不是添加它们。但是当我进入信件,它只是失败,打印吨数字屏幕。但是什么原因导致这个错误?我的意思是,我希望它加载和使用该信的ASCII码。
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 prints tons of numbers to screen. But what causes this error? I mean, I expected it to load and use ASCII code of that letter.
推荐答案
我假设你有这样的代码:
I assume you have code like this:
int n;
while (someCondition) {
std::cin >> n;
.....
std::cout << someOutput;
}
当输入不能读为整数的内容时, :: cin)进入失败状态,并且只要您不处理输入错误,所有后续输入尝试都会失败。
When you enter something that cannot be read as an integer, the stream (std::cin) enters a failed state and all following attempts at input fail as long as you don't deal with the input error.
您可以测试输入操作:
if (!(std::cin >> n)) //failed to read int
,您可以将流恢复到正常状态并丢弃未处理的字符(导致输入失败的输入) :
and you can restore the stream to a good state and discard unprocessed characters (the input that caused the input failure):
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
另一种可能性是接受输入到字符串变量(很少失败),并尝试转换字符串到int。
Another possibility is to accept input into a string variable (which rarely fails) and try to convert the string to int.
这是一个非常常见的输入问题,在这里和其他地方应该有很多线程。
This is a very common problem with input and there should be tons of threads about it here and elsewhere.
这篇关于C ++字符到int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!