What is the best way to check for input errors?

I have a simple code which reads some numbers from a keyboard and I want to make sure that if the users input anything else but numbers he gets an error message and he is taken back to that particular value in order to input it again.

I was thinking at a combination of a try{} catch(){} and goto but I get some weird execution of the program.

1
2
3
4
5
6
7
8
9
10
11
12
  void EuropeanOption::read() {
		cout << "Insert the Stock Price: " << ends;
		cin >> S;
		cout << "Insert the Strike Price: " << ends;
		cin >> K;
		cout << "Insert the Interest Rate: " << ends;
		cin >> r;
		cout << "Insert the Time to Maturity: " << ends;
		cin >> T;
		cout << "Insert the Volatility " << ends;
		cin >> sig;
	}
goto is exceptionally rare in c++. It isn't generally needed, and is reserved for exiting deeply nested logic or loops under rare conditions.

read as a string and validate it, convert to a number, and proceed is the console way.

Gui programs can force the user to only input decent values, for example edit boxes in windows can be set to number type.

you can use error handling but it is probably way overkill.
Last edited on
Topic archived. No new replies allowed.