这是我编写的程序:
#include<iostream>
using namespace std;
int main()
{
int hex[16];
cout << "enter the 16 hexadecimal numbers\n";
for(int i = 0;i < 16;i++)
{
cin >> hex[i];
cout << "input worked\n";
}
}
您能解释一下为什么在我输入“a”后再次显示“输入有效”输出吗? 如果我这样做的话,程序不应该停止吗?
我的意思是为什么在 cin 停止接受输入后“输入工作”行输出?我的意思是如果从 cin 接受输入时出现问题为什么 cout 仍然工作?
最佳答案
您必须通过 std::hex 对其进行管道传输,否则它只接受一个整数,并且您的输入流会在内部切换到错误状态,并且会跳过下一次迭代的输入。这就是为什么您会看到剩余迭代的输出。
cin >> std::hex >> hex[i];
关于c++ - 将字符值输入到 int 数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32666737/