How can I use std::cin.ignore(); to ignore non-numeric characters?

I'm adding this to my Conolse calculator application. If a user types in a non-numeric character, my calculator will go into a fail loop. I was just curious if there is a way to ignore non-numeric characters.

Thanks!
So just input into a numeric variable, then.
cin.peek() and cin.get do the job.

1
2
3
4
5
6
#include <cctype> // isdigit
#include <iostream> // cin

...
        while (!isdigit(cin.peek())) cin.get();
...


Edit:

even so, there are plenty ways of error handling:
this should work, i did not test.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

int main()
{
    using namespace std;
    int input;

    cout << "Enter an integer (type q to quit): ";
    while (cin.peek() != 'q') {
        if (!(cin >> input)) {
            cout << "Please type an integer: ";
            cin.clear();
        } else {
            cout << "You typed " << input << endl;
            cout << "Enter an integer (type q to quit): ";
        }
        while (cin.get() != '\n');
    }
}
Last edited on
Topic archived. No new replies allowed.