i have been trying to find a way to only allow certain inputs by the user to stop the program going crazy when i ask for a number and the user inputs a character(thus going crazy)
this method works but i dont understand why it does, and rather than copy and pasting it every time i need it, i want to know why
Plus my program asks a lot of questions allowing a lot of times where the user is able to make the program go crazy,
is there a more simple or shorter method than this for multiple use of this feature?
#include <iostream>
#include <limits>
usingnamespace std;
int main()
{
bool valid = false;
int input;
while (!valid)
{
if(cin >> input)
{
//this checks whether an integer was entered
if(input < 6 && input > 0)
valid = true;//then we have to see if this integer is in range
}
else
cin.clear(); //some cleaning up
cin.ignore(numeric_limits < streamsize > ::max(), '\n');//empty input stream
if(!valid)
cout << "this input is not valid\n";
}
cout << input << " is between 1 and 5\n";
cin.get();
return 0;
}
I don't necessarily agree with always taking a string input, but that is certainly one way to do it. Read the above and some of the other FAQs. If you enter a character such as 'a' or 'b', I think that your code should execute the else path due to the if statement. That program worked for me. What do you mean by "it goes crazy"?
If I were you, I'd combine the if statements like so if(cin >> input && input < 6 && input > 0)
That way the clear happens regardless of why it fails. As far as why the if statement works, please refer to the FAQ lite. I can't explain it any better then the author.
how is this suppose to convert a string of integers into an int?
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <iostream>
usingnamespace std;
int main()
{
string Text = "456";
int Result;
stringstream convert(Text);
if ( !(convert >> Result) )
Result = 0;
}