Wikipedia:Reference desk/Archives/Computing/2020 December 12

From Wikipedia, the free encyclopedia
Computing desk
< December 11 << Nov | December | Jan >> Current desk >
Welcome to the Wikipedia Computing Reference Desk Archives
The page you are currently viewing is a transcluded archive page. While you can leave answers for any questions shown below, please ask new questions on one of the current reference desk pages.


December 12[edit]

C++[edit]

	int x; 

	for ( x = 0; x != 123; ) 
	{
		cout << "Enter a number: ";

		cin >> x;
	}

When I input an integer other than 123, it yields Enter a number: one at a time.

But why when I input a character such as 'a' by mistake, it yields a recursive Enter a number:Enter a number:Enter a number:Enter a number:Enter a number:Enter a number:Enter a number:Enter a number:Enter a number:Enter a number:Enter a number:Enter a number:Enter a number:............... ?

Thank you for your time!

Stringent Checker (talk) 18:06, 12 December 2020 (UTC)[reply]

Stringent Checker, I hope that this link is helpful. cin does not do a lot of error checking, and so is inadequate for any serious program. It looks like you want to be using stringstream instead. Elizium23 (talk) 20:12, 12 December 2020 (UTC)[reply]
You've just learned the importance of error checking. If the input is incompatible with the type of x, an error gets raised. x is not assigned to, and the input stream is set to a "bad" state. You can check for this by testing the state of std::cin after trying to read from it:
if(!std::cin){std::cerr << "Error" << std::endl; exit(1);}
An exception actually gets raised internally, but for historical reasons it's masked. If we unmask it, then the program throws an exception on invalid input. See for yourself by putting this at the start of the program:
std::cin.exceptions(std::istream::failbit);
If you're wondering, I'm avoiding using namespace std because many consider that bad practice. And, Elizium23 is correct that for more "serious" programs you generally want to use stringstream or a third-party library that gives more robust input handling. --47.152.93.24 (talk) 05:08, 13 December 2020 (UTC)[reply]
Thank you folks for your generosity!! Getting better together! Stringent Checker (talk) 19:22, 13 December 2020 (UTC)[reply]