如何在终止前强制输入

How do I force to input before termination?

本文关键字:输入 终止      更新时间:2023-10-16

这是我的代码的摘录,问题就在这里。

    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;