3

我知道如何在 C 中做到这一点,但不知道 C++ 解决方案。我希望以下内容具有故障安全性,但是在为输入提供字符串甚至字符后,程序会挂起。如何读取包含 \n 的输入流以释放它?

int main() {
    int num;
    do { 
        std::cin.clear();
        std::cin >> num;
        while ( std::cin.get() != '\n' );
    } while ( !std::cin.good() || num > 5 );
    return 0;
}
4

5 回答 5

2

一旦流处于错误状态,所有读取操作都将失败。这意味着,如果cin >> num读取失败,带有调用的循环get()将永远不会结束:所有这些get()s 都将失败。只有在清除错误状态后才能跳到行尾。

于 2012-12-20T10:36:37.130 回答
1

要在 R. Martinho Fernandes 的回答之上构建,这里有一个可能的 C++ 替代代码:

std::string num;
std::getline(std::cin, num);

// Arbitrary logic, e.g.: remove non digit characters from num
num.erase(std::remove_if(num.begin(), num.end(),
            std::not1(std::ptr_fun((int(*)(int))std::isdigit))), num.end());

std::stringstream ss(num);
ss >> n;
  • std::getline函数从 中提取字符cin并将其存储到num。它还提取并丢弃输入末尾的分隔符(您可以指定自己的分隔符或\n将使用)。
  • string::erase函数使用否定谓词从num字符串中删除除数字以外的所有字符。std::remove_ifstd::isdigit
  • 然后使用 a 将字符串表示为整数std::stringstream(aboost::lexical_cast也可以)

此处由擦除功能实现的逻辑可以是任何其他逻辑,但此代码可能比问题中包含的代码更易于阅读。

于 2012-12-20T11:44:27.883 回答
0

我会使用 getline(cin,num) 来处理它,然后使用 cin.fail() 捕获任何失败。我通常将 cin.fail() 与整数一起使用,但理论上也应该与字符串和字符一起使用,例如:

    string num;
    getline(cin,num);
    if(cin.fail())
    {
      cin.clear();
      cin.ignore();
    }
于 2012-12-20T12:07:10.307 回答
0

One way would be to check the state after every input and throw an exception if that happens for example:

#include<iostream>
using namespace std;

int main(){

int a;
cout<<"Enter a number: ";
cin>>a;

//If a non number is entered, the stream goes into a fail state
try
{
    if(cin.fail()){
        throw 0;
        cin.clear();
        cin.ignore();
    }
}
catch(int){
    cin.clear();
    cin.ignore();
}
return 0;
}

After that you can continue with whatever code you wish

于 2014-11-23T20:45:25.397 回答
0

To clear input stream, use cin.sync() . no need to use cin.clear() or cin.ignore().

于 2016-05-10T20:31:02.110 回答