clearing cin buffer

Jul 10, 2014 at 5:19pm
I am having some issue with clearing cin buffer. The following code does not wait for me to see the output window and till I hit return character.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include "iostream"
#include "stdio.h"
#include "math.h"
#include "string"
#include "sstream"
using namespace std;

int main(){
	int num;
	cout << "Enter the number to print factors: ";
	cin>>num;
	cin.clear();
	std::cin.ignore(INT_MAX, '\n');
	cout << "1*" << num << endl; //printing the first factor of number * 1
	printFactors("", 1,num);
	getchar();
	return 0;
}


I tried cin.flush, cin.ignore(numeric_limits<streamsize>::max(), '\n'); cin.clear(); fflush(stdin);. None of them worked

I am working on Microsoft visual studio express 2013 for windows desktop
Last edited on Jul 10, 2014 at 7:18pm
Jul 10, 2014 at 8:17pm
> The following code does not wait for me to see the output window
If you mean that it doesn't stop at line 14, that's because you've pressed <Return> after inputting the number

If you mean at line 16, then we'll need to see `printFactors()' definition
Jul 10, 2014 at 9:46pm
It is a design flaw to summarily ignore input.

Your program should prefer to properly synchronize with the expected input. To that end, you really only need to remember one basic premise:


The user will always press ENTER after an input.


This is what the user expects. Ask his (or her) name and he types it, then presses Enter. Ask his age and he types it and presses Enter.

I personally think all input should be read as a string (using getline()), and then processed. This saves you all kinds of grief.

Otherwise you must pay attention to cin.ignore() at all the appropriate spots.

Hope this helps.
Jul 11, 2014 at 4:21am
Thanks Duoas and ne555, that was helpful.
Topic archived. No new replies allowed.