1

One part of my program: Let user input a series of integer, and then put them into an array.

int n=0;
cout<<"Input the number of data:";
cin>>n;
cout<<"Input the series of data:";
int a[50];
for(i=0; i<n; i++)
{
    cin>>a[i];

}

Then, when user input wrong data such as a character 'a' or 'b'. The program will go into an infinite loop.

How to catch the wrong cin? How to clear the buffer and give user the chance to input a right data again?

Yingli Yan
  • 69
  • 1
  • 8
  • Remember that input (and output) streams can be used in [boolean expressions](http://en.cppreference.com/w/cpp/io/basic_ios/operator_bool), like in an `if` statement. – Some programmer dude Mar 05 '14 at 09:28

2 Answers2

4

Simply check if the input is a number first and then append it to the array

    int x;
    std::cin >> x;
    while(std::cin.fail())
    {
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
        std::cout << "Bad entry.  Enter a NUMBER: ";
        std::cin >> x;
    }

    a[i] = x;
const_ref
  • 4,016
  • 3
  • 23
  • 38
1

Clear the cin state and ignore bad input.

for(i=0; i<n; i++)
{
    while (!(cin>>a[i])) {
        cin.clear();
        cin.ignore(256,'\n');
        cout << "Bad Input, Please re-enter";
    }
}
Abhishek Bansal
  • 12,589
  • 4
  • 31
  • 46