C++字符为int

Vit*_*Vit 9 c++

当你cin >>写入int变量时会发生什么?我尝试使用简单的代码添加2个int数字,首先读取它们,然后添加它们.但是当我输入信件时,它就会失败并打印出大量的数字.但是什么导致了这个错误?我的意思是,我希望它加载并使用该字母的ASCII码.

vis*_*tor 10

我假设你有这样的代码:

int n;
while (someCondition) {
    std::cin >> n;
    .....
    std::cout << someOutput;
}
Run Code Online (Sandbox Code Playgroud)

当您输入无法读取为整数的内容时,只要您不处理输入错误,流(std :: cin)就会进入失败状态,并且所有后续输入尝试都会失败.

您可以测试输入操作的成功:

if (!(std::cin >> n)) //failed to read int
Run Code Online (Sandbox Code Playgroud)

并且您可以将流恢复到良好状态并丢弃未处理的字符(导致输入失败的输入):

std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Run Code Online (Sandbox Code Playgroud)

另一种可能性是接受输入到字符串变量(很少失败)并尝试将字符串转换为int.

这是一个非常常见的输入问题,在这里和其他地方应该有很多关于它的线程.


Ton*_*ion 3

如果你显式地将 char 转换为 int,它将使用 ASCII 代码,否则它不会自行转换为 int,因此你会得到奇怪的结果。