Prompting the user to re-enter if entered value is not int

I got a little problem. The user is supposed to enter a number.But if the user accidentally entered a non number (like char) it'll prompt the user to re-enter the value along with the sentence " Enter Value:". I tried switch and case bt i cant find a term which is non double. Initial code below.
1
2
3
Default code
cout<<"Enter value:"
cin>>x

Thanks in advance.
Last edited on
Read this article: http://www.cplusplus.com/forum/articles/6046/ the code example does exactly what you are trying
Oh okay thanks!!!! I don't really understand why when you enter a non int at the int part it ask you to enter again.
Here is that part of code, Ive re-commented the lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 string input = "";
 int myNumber = 0;

 while (true)  // loop until explicit stop ( break )
 {
   cout << "Please enter a valid number: ";
   getline(cin, input); // get input into a string 

   // This code converts from string to number safely.
   stringstream myStream(input); // creates a new stream with the contents of the input given by the user
   if (myStream >> myNumber) // get the input to your variable, if it is a valid number this expression would be true
     break; // end the loop
   cout << "Invalid number, please try again" << endl; // the loop is sill running, this means that the input wasn't good
 }
 cout << "You entered: " << myNumber << endl << endl; // the loop has ended and myNumber would hold the value 

Cool, thanks so much !!!
Topic archived. No new replies allowed.