In the case the user types in a character instead of a number for a float, I put a loop that checks if the value of the float is equal to 0 since if they input a character the value should be 0.
1) From the code, when I type in a letter I get infinite "Error"'s. Why doesn't the second cin ask for input and how can I fix that?
2) In case they really DO type in 0 it will still give error, although not infinite errors for some reason. Is there a different way to make sure the value of the input is not equal to a letter to bypass this problem?
If you want to ensure it is a floating point instead of just a normal integer you may have to read everything into a string and parse it to see it has correct format using std::getline and std::stringstream
You need to clear error state of the input and also the remove the bad input to avoid getting an infinite loop of Errors. You can do something like this to check. This is an easy way to check for bad input
1 2 3 4 5 6
if (cin.fail()) //checking whether failbit or badbit is set
{
cout<<"error";
cin.clear(); //sets a new value for the stream's internal error state flags.
cin.ignore(numeric_limits<streamsize>::max(),'\n'); //ignores rest of the input ..
}
But if you want to completely ensure that it is a number you need to do as giblit suggested and do something like this
int only_int(constchar *output)//To checking if input is integer
{
int check;
string user_input;
cout<<output<<endl;
while(1)
{
getline(cin,user_input);//gets user input as a string
stringstream convert(user_input);//makes string into a stream
if(convert >> check &&!(convert >> user_input))//checking for valid conversion and any rejects if any unconverted input left
{
return check;
}
else
{
cin.clear();
cout<<"ERROR!\nwrong input\nPlease enter a NATURAL NUMBER only"<<endl;
}
}
}
I suppose none. It's just less verbose and more common. Also, I tend to keep one style instead of using two styles. You use the fail method then the operator ! method later on.
Also you don't need the cin >> input if you are using getline and also you want to avoid using getline after [/code]cin >>[/code] since the latter leaves a newline in the buffer if you wish to use it like that you are going to need to ignore the newline(and possibly other things) left in the buffer. std::cin.ignore(1024, '\n'); //or std::numeric_limits<std::streamsize>::max() instead of 1024