Program delay with getch();

Jan 20, 2009 at 2:29pm
closed account (42hU7k9E)
Basic program, you have to press a key, and if the key is for example 'a', the program inputs "LOL", or smth like that, I hope you understand what I mean. The problem is that the program does not do things like it should.
1
2
3
4
5
6
7
8
9
10
	
while(c!=13)
{
	c=getch();
	if(c=='x')
	{
		cout << "LOL";
	}
		
}


I press x for 3 tiem and the program does nothing, and when I press enter(ASCII value=13) the program inputs "LOL" for three time.
q:Why doesnt the program inputs the "LOL" immediately?
Jan 20, 2009 at 6:54pm
cout is buffered. That is, it may not generate output immediately. Why? Because if you're sending a lot of output, it's more efficient to do it that way.

You can force the stream to flush it's contents by calling the flush method. However, writing an end of line with endl also calls flush, as that seems like a reasonable time to do it.
Jan 21, 2009 at 4:22pm
closed account (42hU7k9E)
Since I know nothing about flush(yet), I solved the problem by exchanging the cout with printf.
Jan 21, 2009 at 4:56pm
cout (C++) is better that printf (C)
flush is just a simple manipulator cout << "something" << flush;
http://www.cplusplus.com/reference/iostream/manipulators/flush.html
Topic archived. No new replies allowed.