-
Checking Floats
How would I go about checking to see if a cin >> input is a number/float? I'm making a really basic calculator, which works fine, unless you put in letters or symbols. Then you get some really funky results. LOL
Here's what I have so far:
Code:
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string action;
float f_n;
float s_n;
cout << "\n\n What do you want to do? (Possible answers: multiply, add, subtract, divide) \n";
cin >> action;
if (action != "add" && action != "subtract" && action != "multiply" && action != "divide")
{
cout << "Unknown action command.";
return 1;
}
cout << "\n\n First Number \n";
cin >> f_n;
// Somehow check to see if "f_n" is an int/float....
cout << "\n\n Second Number \n";
cin >> s_n;
// Somehow check to see if "s_n" is an int/float....
if (action == "add")
{
cout << "Your answer is >> " << f_n + s_n << " \n\n";
}
else if (action == "subtract")
{
cout << "Your answer is >> " << f_n - s_n << " \n\n";
}
else if (action == "multiply")
{
cout << "Your answer is >> " << f_n * s_n << " \n\n";
}
else if (action == "divide")
{
cout << "\n\n Your answer is >> " << f_n / s_n << " \n\n";
}
else
{
cout << "\n\n unknown operation" << " \n\n";
return 1;
}
return 0;
}
-
Check the result of cin >> f_n.
-
And how do I do that? That's kinda what I was asking. Thanks for your help, BTW. :)
-
It could be along the lines of:
Code:
if (!(cin >> f_n))
{
cout << "Invalid input" << endl;
// exit program here?
}
-
If you check documentation for stream objects, you will find they support an operator!() which gives the error state. If an istream is in an error state after attempting to read a float, a float has not been successfully read in. Note that any error state will need to be cleared before attempting to read anything else.
-
Okay, thanks, peeps. I'll check the documentation, and see where I get with that. If its anything like the PHP manual, I'm all set with reading for the next six months. XD