我正在学习 C++ 并在学习过程中编写小程序。下面是一个这样的程序:
// This program is intended to take any integer and convert to the
// corresponding signed char.
#include <iostream>
int main()
{
signed char sch = 0;
int n = 0;
while(true){
std::cin >> n;
sch = n;
std::cout << n << " --> " << sch << std::endl;
}
}
当我运行这个程序并将输入保持在相当小的绝对值时,它的行为符合预期。但是当我输入更大的输入时,例如 10000000000,程序会重复吐出相同的输出。某些输入组合会导致不稳定的行为。例如:
#: ./int2ch
10
10 -->
10000000000
10 -->
10 -->
10 -->
10 -->
程序吐出“10 -->”直到它被杀死。 (对于这种特定的输入序列,程序的输出会不规律地改变速度。)我还注意到,大值的输出取决于先前的合法输入以及当前非法输入的值。
这是怎么回事? (我不关心修复程序,这很容易。我想了解它。)
基本上您的 cin
流处于失败状态,因此当您尝试读取它时会立即返回。像这样重写您的示例:
#include <iostream>
int main()
{
signed char sch = 0;
int n = 0;
while(std::cin >> n){
sch = n;
std::cout << n << " --> " << sch << std::endl;
}
}
cin >> n
将返回对 cin
的引用,您可以在条件中测试它的“良好性”。所以基本上“while(std::cin >> n)
”是说“虽然我仍然可以成功地从标准输入读取,但执行以下操作”
编辑:它重复输出输入的最后一个好值的原因是因为那是在 n 中成功读取的最后一个值,读取失败不会改变 n 的值
编辑:如评论中所述,您可以清除错误状态并重试,这样的操作可能会起作用,而只是忽略错误的数字:
#include <iostream>
#include <climits>
int main() {
signed char sch = 0;
int n = 0;
while(true) {
if(std::cin >> n) {
sch = n;
std::cout << n << " --> " << sch << std::endl;
} else {
std::cin.clear(); // clear error state
std::cin.ignore(INT_MAX, '\n'); // ignore this line we couldn't read it
}
}
}