2

I want the program to loop until the input is valid (x is an int, and x>0), but my program accepts the input when I give it 1,1 and loops infinitely when I give a string to it, repeating "Wrong input!".

#include <iostream>

using namespace std;

int main()
{
    bool fail;
    int x;
    do{
        cin >> x;
        fail=(cin.fail() || x<=0);
        if (fail){
            cout << "Wrong input!" <<endl;
            cin.clear();
        };
    }while(fail);
    return 0;
}
R2DToo
  • 33
  • 3

2 Answers2

2

Use standard member function ignore in the if statement. For example

std::cin.ignore(std::numeric_limits<std::streamsize>::max(),’\n’);

or just

std::cin.ignore();

It is used to skip invalid symbols in the buffer.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

You may read an entire line and convert the line with a string stream:

#include <iostream>
#include <sstream>

int main()
{
    bool fail;
    int x;
    do{
        std::string line;
        fail = ! getline(std::cin, line);
        if( ! fail) {
            std::istringstream s(line);
            fail = ! (s >> x) 
                || x < 0  
                || ! s.eof(); // The entire line represents an integer
        }
        if(fail) {
            std::cout << "Wrong input!" << std::endl;
        };
    } while(fail);
    return 0;
}