I have a task to make a program that will calculate two numbers put into it. And also show the calculation between every number.

And if I input a letter not a number the program crashes, this is an more advanced task that I dont need to do but I really want to know how to do this. So that is my question, how do I make the program give me a warning that not to use letters and still give u ability to input numbers if you enter a letter, instead of crashing.
This is how my code looks so far
Blockquote
float nmr1, nmr2;
cout << "Write two numbers.\n";
cin >> nmr1;
cin >> nmr2;
cout << "\n";
cout << nmr1 << " + " << nmr2 << " = " << nmr1 + nmr2 << endl;
cout << nmr1 << " - " << nmr2 << " = " << nmr1 - nmr2 << endl;
cout << nmr1 << " * " << nmr2 << " = " << nmr1 * nmr2 << endl;
cout << nmr1 << " / " << nmr2 << " = " << nmr1 / nmr2 << endl;
cin.get();
cin.get();
return 0;
maybe there are easier things to write but I'm a beginner, and I would use the search tool but I don't know what to search.
cin >> var_of_type_float will return false if the input fails. So simply use that in a conditional expression, something like:
if (cin >> nmr1) { // all ok
If you want to check the input, usual way is to read a string, check if there are non valid character, then parse it into a number (tedious task in C++ with real numbers) and store in a float, finally, perform operations with those floats.
If you are not working with text input yet, I recommend you to wait to implement this feature, as it could be complex for a beginner in programming
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With