I have a problem restricting user possibility to enter a caracter while I ask him to enter number

I want to prevent my program from blocking. I don't know how to say this in C++ language, I will try with my words.
1
2
3
4
while( (answer == character) || (answer == string of characters) ){
cout<<"You need to enter a number";
cin>>answer;
} 

Hope you understood...:D
If anyone can help me, please help me.:) Thanks in advance!
Last edited on
If you ask the user to enter a number (with cin >> or scanf, etc), only number can be entered. Non-numeric character simply remains unprocessed, and you're expected to write code that either ignores it, or reads it off into a non-number variable.

To illustrate,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <string>
#include <limits>
using namespace std;
int main()
{
    cout << "Please, enter a number\n";
    int n; // n is a number, it cannot be anything else
    // cin >> n reads a number. If the input is not a number, 
    // it does not read it at all, it sets the error flag on cin and retunrs it
    // so we check that condition in a loop:
    while( !(cin >> n) )
    {
        cout << "You need to enter a number\n";
        cin.clear(); // reset the error flags
        // here you still have unprocessed input. You have options:
        // 1. ignore:
      cin.ignore(numeric_limits<streamsize>::max(), '\n');
        // 2. read into a string
//        string str;
//        getline(cin, str);
        // 3. read into char (in a loop, since there may be many)
//        char c;
//        while(cin.get(c) && c != '\n')
//        {
//        }
    }
    cout << "Thank you for entering the number " << n << '\n';
}

demo: http://ideone.com/XbL1wD
Any simple methods? By the way, Cubbi's help helped....
Topic archived. No new replies allowed.