Click here to Skip to main content
15,881,248 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Usually we put a getchar at the end of a console application as a command to close the program.
But getchar confuse with cin orders i guess and sometimes i have to put more than just one getchar at the end of the program. such as below,
how should i fix it? (I mean what should i do to have only one getchar at the end?)
C++
int main(){
	vector<int> numbers(0);
	cout << "please enter you numbers :::\n''entering any characters but numbers is the end of entry''\n";	
	int counter = 0;	
		do{			
			int newnumber = 0;
			cout << "element(" << counter << ") = ";
			counter++;
			cin >> newnumber;
			numbers.push_back(newnumber);
			if (cin.fail()){
				cout << "entered numbers are:\n";
				for (vector<int>::iterator i = numbers.begin(); i != numbers.end(); i++)
				{
					cout << *i;
					if (i != numbers.end()-1)cout << " - ";
				}				
			}
		} while (cin.good());
// here
		getchar(); getchar(); getchar();
}
Posted

The problem is that some characters may already be present in the input buffer.
Depending on many buffered inputs are there you need more getchar.
A simple solution is to loop while a '\n' is ecountered de facto empting also the buffer:
C++
int c;
do
    c=getchar();
while (c!=EOF && c!='\n');


Another really classic solution (coming from DOS times, but still working) is:
C++
while(_kbhit())
    _getch();

With the latter solution you don't need to have a '\n' in the stream buffer.
 
Share this answer
 
v3
Use cin.get() instead.
 
Share this answer
 
Comments
m.r.m.40 30-Jan-15 7:10am    
I made it like newnumber = cin.get();
which it doesn't work, and when I input a alphabet character it should stop working but it still gets the character and ask for the next inputm and it shouldn't be working like that.
Richard MacCutchan 30-Jan-15 7:38am    
Sorry, try getline(), it should read everything that's left in the input buffer.
Frankie-C 30-Jan-15 7:55am    
getline requires a '\n' to return
Richard MacCutchan 30-Jan-15 7:59am    
I know, that's why I suggested it.
I forgot that MS allows the use of fflush() also on input streams, so this simple line should do:
C++
fflush(stdin);
 
Share this answer
 
What's your point? If called from console, why wait to close the program? If this is a debugging concern, why not simply place a brekpoint?

That said, do read up the suggestions posted here: http://stackoverflow.com/questions/24776262/pause-console-in-c-program[^]

P.S.: in another stackoverflow thread, someone suggested cin.ignore(). Apparently this would request another line of input, but ignore the entered string, to the effect that your program would wait for the next [enter] key.
 
Share this answer
 
v2

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