Click here to Skip to main content
15,905,322 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Attached is my programming homework. I was trying to deal with inputs that are neither expected integers nor EOF. I noticed that to avoid infinite loops I had to flush out cin before reading next input, but:

1. I'm not entirely sure why. Is it because a wrong input is just put back into the input stream?

2. Why is cin.ignore() alone not enough to stop infinite loops?

3. What confuses me most is I can't tell the difference between
cin.clear() then cin.ignore() and
cin.ignore() then cin.clear()
Apparently only the former order works. But what does stream error state have to do with dumping a stream?

C++
#include<iostream>
#include<iomanip>

using namespace std;

int main()
{
	int num;
	
	cout << "Please enter a decimal number: ";
	cin >> num;

	while (!cin.eof())
	{
		if (!cin.fail())
		{
			cout << "Its hexadecimal format is: " << setbase(16) << num << endl;
			cout << "Its octal format is: " << setbase(8) << num << endl;
		}
		cout << "Please enter a decimal number: ";
		cin.clear();
		cin.ignore(numeric_limits<streamsize>::max(), '\n');
		cin >> num;
	}

	return 0;
}
Posted
Updated 31-Mar-15 17:36pm
v4

1 solution

cin.ignore is a stream input function[^]: it reads characters from the stream until, in your case, the character '\n' is read (it doesn't store those characters anywhere, unlike other input functions, but it examines and counts them).

While any error flag is raised, input functions do not read any characters (they do a few other things[^], but they aren't relevant here). Once the flag is cleared with cin.clear(), cin.ignore (or getline(cin, str), or cin.get() or any other input) can proceed.
 
Share this answer
 
Comments
Member 11212276 1-Apr-15 22:41pm    
Thank you very much for your help!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900