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; }



LinkBack URL
About LinkBacks


