0

I am new to C++ and was attempting to create a basic program. To ask for two values and store the result in separate variables as shown below:

#include <iostream>

using namespace std;

int main () {

int sizeOfArray = -1, bufferSize = -1;

while (true){
cout << "Enter the size of the array: " << endl;
cin >> sizeOfArray;
if (cin.fail())
cin.clear();


cout << "Enter the size of the buffer (k): " << endl;
cin >> bufferSize;
if (cin.fail())
cin.clear();


if (sizeOfArray > 0 && bufferSize > 0){
break;
} 

}

 return 0;
}

However, when entering a value that is not of type int instead of clearing and asking for the next input I run into an infinite while loop as shown below:

Enter the size of the array: Enter the size of the buffer (k): Enter the size of the array: Enter the size of the buffer (k): Enter the size of the array: Enter the size of the buffer (k): Enter the size of the array: Enter the size of the buffer (k): Enter the size of the array: Enter the size of the buffer (k): Enter the size of the array: Enter the size of the buffer (k): Enter the size of the array: Enter the size of the buffer (k): Enter the size of the array: Enter the size of the buffer (k): ^C

Sandup
  • 1

1 Answers1

1

cin.clear() clears the state of cin. It does not remove the problematic input from the stream. You need to add code to ignore rest of the line.

if (cin.fail())
{
   cin.clear();
   cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

Add

#include <limits>

to be able to use std::numeric_limits.

Read more about std::istream::ignore.

R Sahu
  • 204,454
  • 14
  • 159
  • 270