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>
usingnamespace std;
int main(){
int num;
do{
cout<<"Type a positive number";
cin>>num;
}while (num<0);
cin.get();
cout<<"the number is: "<<num;
}
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.
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/