Hello guys. I wanted to know how to make my program safe against lazy people. For example, let's say I want the user to enter an int. Cause he's dumb, his input will be dfandoanfvoasdmpsnossjkdqwjdajdncasdfvdavdvasasdfd or 68469165465161616165161616165165165164164654 or 84+5+f44+6sdc4+ad65fbsdf+6bvsdf65fgs4df+g8sf+f+9g54dsf+dsf, and my program will explode. How can I prevent this to happen?
I use cin.fail() to check if they entered something other than what my variable should hold. (like a letter into an integer). Then i clear the stream and the buffer and then ask them to enter a correct input again.
Something like this:
1 2 3 4 5 6 7
cin >> num;
if (cin.fail())
{
cout << "Enter a number, not a letter dum dum!" << endl;
cin.clear(); //clear stream
cin.ignore(80, '\n'); //clear 80 characters until a \n is reached.
}
#include <iostream>
#include <sstream>
int get_int(int min, int max, std::string prompt)
{
int i;
std::string str;
while(true) {
std::cout << prompt << std::endl;
getline(std::cin, str, '\n'); //get a string terminated by end-of-line.
std::stringstream ss(str); //copy the string to an input stream.
//ss >> i converts the stream to an integer. This will fail something like "g45" but not fail if "45g" is entered.
//!(ss >> str) checks to see if more characters are left; if so, it fails. The "45g" example would fail here.
if(ss >> i && !(ss >> str) && i>=min && i<=max) return i;
//if you get here, you didn't get your integer.
std::cin.clear(); //clears any cin errors, like eof(). Protects against 'ctrl-z' etc.
std::cerr << "You must enter an integer between " << min << " and " << max << ".\n";
}
}
int main()
{
int i=get_int(1, 10, "Enter a number between 1 and 10: ");
std::cout << i;
std::cin.get();
return 0;
}