How to check if the input is a valid integer without any other chars?

后端 未结 7 1853
故里飘歌
故里飘歌 2020-11-28 15:36
#include 
#include 

using namespace std;

int main()
{
    int x;
    cout << \"5 + 4 = \";
    while(!(cin >> x)){
               


        
相关标签:
7条回答
  • 2020-11-28 16:16

    You have a line oriented input, so you should probably be using getline. Something like:

    bool
    getIntFromLine( std::istream& source, int& results )
    {
        std::string line;
        std::getline( source, line );
        std::istringstream parse( source ? line : "" );
        return parse >> results >> std::ws && parse.get() == EOF;
    }
    

    should do the trick.

    Using this, your loop would be:

    while ( !getIntFromLine( std::istream, x ) ) {
        std::cout << "Error, please try again." << std::endl;
    }
    

    Note that this technique also means that you don't have to worry about clearing the error or resynchronizing the input.

    0 讨论(0)
提交回复
热议问题