std::cin doesn't throw an exception on bad input

前端 未结 2 568
天命终不由人
天命终不由人 2020-12-20 00:34

I am just trying to write a simple program that reads from cin, then validates that the input is an integer. If it does, I will break out of my while loop. If not, I will as

2条回答
  •  遥遥无期
    2020-12-20 01:12

    Don't use using namespace std; Instead import what you need.

    It's better to do input a line at a time. This makes behavior much more intuitive if you have multiple words on one line, or if you press enter before typing anything.

    #include 
    #include 
    #include 
    
    using std::cerr;
    using std::cin;
    using std::cout;
    using std::endl;
    using std::flush;
    using std::getline;
    using std::istringstream;
    using std::string;
    
    int main() {
        int input;
        while (true)
        {
            cout << "Please enter an integral value: " << flush;
            string line;
            if (!getline(cin, line)) {
                cerr << "input failed" << endl;
                return 1;
            }
            istringstream line_stream(line);
            char extra;
            if (line_stream >> input && !(line_stream >> extra))
                break;
        }
        cout << input << endl;
        return 0;
    }
    

提交回复
热议问题