Pradana Pradana - 16 days ago 5
C++ Question

While function skips line in C++

I currently have this function:

double GrabNumber() {
double x;
cin >> x;
while (cin.fail()) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "You can only type numbers!\nEnter the number: ";
cin >> x;
}
return x;
}


Its purpose is to check if
x
is a valid number, returning it if it is valid or repeating
cin >> x
if it is not.

It's called during this function:

void addition() {
cout << "\nEnter the first number: ";
double a = GrabNumber();
cout << "Enter the second number: ";
double b = GrabNumber();
// rest of code


When I type for example "6+" when it tells me to enter the first number, it accepts it but immediately goes to the second line and calls it an error where I haven't even entered my input.

I assume this is because the first input only accepts "6" while "+" goes to the second input returning an error. Therefore, there must be an issue with the parameters of
while
.

Answer

If your input is immediately successful, you don't ignore the rest of the line, which ends up into the next input. This can be fixed by simply duplicating the cin.ignore call.

double GrabNumber() {
    double x;
    cin >> x;

    cin.ignore(numeric_limits<streamsize>::max(), '\n'); // <--

    while (cin.fail()) {
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        cout << "You can only type numbers!\nEnter the number: ";
        cin >> x;
    }
    return x;
}

I'll leave DRYing this code as an exercise ;)