Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ how to stop from crashing if entering letters

Tags:

c++

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

Console

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.

like image 526
FatDog Avatar asked Nov 25 '25 08:11

FatDog


2 Answers

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
like image 100
Paul Evans Avatar answered Nov 26 '25 23:11

Paul Evans


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

like image 21
angrykoala Avatar answered Nov 26 '25 23:11

angrykoala



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!