cin assigns beginning of string to int, only fails in second call

北城余情 提交于 2021-01-27 12:01:52

问题


In the snippet

for(;;) {

    std::cout << "Please enter an integer: ";
    if(std::cin >> nInput) {
        return nInput;
    }
    else {
        std::cout << "Invalid input! Please enter an integer!\n";
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }

}

cin will assign the beginning of a string to nInput, provided at least the first character is numeric. For instance, here's some of my console output:

Please enter an integer: 10
Please enter an integer: foo
Invalid input! Please enter an integer!
Please enter an integer: 20bar                                       //this will return 20, leave "bar" in the stream. Until the next cin call, cin.good() returns true
Please enter an integer: Invalid input! Please enter an integer!     //fails because "bar is in the stream"
Please enter an integer: -1

How do I check keep cin from returning "20" when the user inputs "20bar"? Alternatively, how can I check for more content in the cin buffer?


回答1:


In situations like this you should read the data into a std::string and then check the string to see if you have valid input. cin >> is perfectly happy with 20anything_here as input for an integer type as it just stops reading once it finds the non integer part.

Once you parse the string and determine that it meets your requirements you can use std::stoi to convert the string to an int




回答2:


One option is to read the number followed by a character. Iff the following character is '\n' it means they typed the number without anything afterwards:

if ( (std::cin >> nInput) && std::cin.get() == '\n' )


来源:https://stackoverflow.com/questions/35301679/cin-assigns-beginning-of-string-to-int-only-fails-in-second-call

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!