如何在终止前强制输入
How do I force to input before termination?
这是我的代码的摘录,问题就在这里。
long long user_largest_plus;
long long user_largest_minus;
cout << "Input the largest+1 in decimal: " << endl;
cin >> user_largest_plus;
//cout << endl;
// cout << "Input the largest-1 in decimal: " << endl;
cin >> user_largest_minus;
cout << endl;
cout << "In decimal plus: " << user_largest_plus;
cout << endl;
cout << "In decimal minus: " << user_largest_minus;
只要我输入9223372036854775808到user_largest_plus
,执行将终止。也就是说,我不能输入user_largest_minus
。我正在使用Code::Blocks, MinGW编译器。
是因为我刚刚溢出了变量,错误触发了这个终止吗?还有别的办法吗?
顺便说一下,这个数字是2^63 - 1
,我可以存储的最大数字。
谢谢
尝试替换
cin >> user_largest_plus;
if( !( cin >> user_largest_plus ) ) {
user_largest_plus = 0;
cin.clear();
cout << "Bad input. Using zero insteadn";
}
当输入文本不是有效的long long
时,会发生两件有趣的事情:
-
user_largest_plus
从未设置, -
bad
位设置在cin
。
提供的代码设置一些值为user_largest_plus
,以避免未定义的行为,并清除坏位,因此cin
仍然可以使用
假设这是因为输入的数字太大(并且为了防止用户输入APPLE
作为大小时出现错误),您应该这样做:
string user_largest_plus_string;
long long user_largest_plus;
cout << "Input the largest+1 in decimal: " << endl;
cin >> user_largest_plus_string;
user_largest_plus = atoi(user_largest_plus_string.c_str());
if (user_largest_plus == 0)
throw std::runtime_error("User entered something besides a number!");
cout << "largest+1 is now " << user_largest_plus << "." << endl;
相关文章:
- 在输入句子时终止 std::out_of_range
- 在这个无限循环中,当输入 0 时终止,当输入 int 范围之外的任何内容时,程序行为不正常
- 代码在执行之前终止,并且没有从用户那里获取输入
- 使用终止程序的指针在数组中输入字符串
- 程序在终止循环后不接收输入
- 如何用字符终止整数输入循环?
- 当我输入非整数值时,我的二次方程代码终止,如何让它正确循环?
- 程序终止,状态为 -1073741510 在 for 循环的中间,将输入分配给二维数组
- 程序终止,而不是继续整数输入验证循环
- 如何在C++中终止具有键盘输入的侦听 TCP 服务器
- 如何在C++中使用 if 语句终止向量输入
- (C++) 学习向量 - 编码/输入流终止/比较向量的问题
- 当用户输入 -1 时,它应该终止
- 如何将键盘输入终止
- C++循环未终止时的输入验证
- C++输入超过 11 个整数时程序终止
- cin函数是否添加了在输入结束时终止的null
- 是否有一种方法可以在输入负数时平均不包括负数,这是您终止程序的方式
- 如何通过输入终止数据输入
- 终止将输入读取到int中的内容