Not allow to type char string on a int value

Hi again :-)

I want to know how to avoid to type by error a char string on a int variable or, at least, avoid to try saving the char string to the variable.
Because my program crashes becomes mad, or run incorreectly, when this happens!
Here's a simple example code (the original one is too long to post):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <cstdio>
#include <conio2.h>
#include <string>
using namespace std;
int main(){
    int num;
    do{
    cout<<"Type a positive number";
    cin>>num;
    }while (num<0);
    cin.get();
    cout<<"the number is: "<<num;
}

If I accidentally type a letter sometimes (often simply closes or hangs), I get this:
http://img63.imageshack.us/img63/1755/crashe.png

Many thanks.

Last edited on
cin tries to read an int but it can't find an int in the stream, instead it turns on it's fail bit flag. The input character remains in the stream so cin will always try to read that forever since it's in a loop.

try to add this at the end of your loop
1
2
3
4
if( !cin.good() ) {
	cout << "Oooops! Error, something is wrong..\n\n";
	return EXIT_FAILURE;
}

http://cplusplus.com/reference/iostream/ios/good/


TIP: ALT+PrintScreen will capture only the active window, saves time from editing.
I don't think that crashing is a very useful answer to a bad input.

Your problem is a common one. Here is a post that dealt with a similar problem: verify that integer within specific range is entered. (You don't have to check the range of the integer, of course, but the rest is good):
http://www.cplusplus.com/forum/beginner/18258/

Another way of handling it is to read the entire line of input, and use a stringstream to test its validity:
http://www.cplusplus.com/forum/beginner/4174/page1.html#msg18298

This last one is a fancy class to make sure the user didn't ENTER something like "12xyz" when asked for a number. The stuff that relates to what you are interested in is in the main() function.
http://www.cplusplus.com/forum/beginner/13044/page1.html#msg62827

Hope this helps.
Topic archived. No new replies allowed.