> Can you help me with this c++ programme?

Can you help me with this c++ programme?

Posted at: 2014-12-18 
The problem here is that cin uses a buffered input stream.

What does that mean?

It means that when you call cin.get(a), then you type a character, the function does *not* return control back to you with a set to the character you just typed. Instead, that character is just put into a buffer. And if you type more characters, they are also just put into the buffer. (And if you hit backspace, the last character is removed from the buffer).

So when do these characters finally get moved out of the buffer and given back to your program? When you hit the enter key. So....in order to get cin.get(a) to return even one character, you have to hit the enter key. Then cin.get(a); will return one character at a time from that buffer each time you call cin.get(a);

And that includes the enter key, which will be the last character returned.

In order to get your loop to display anything, the user has to hit the enter key. But hitting the enter key will cause your while loop to exit, because that is your exit condition. Bit of a Catch-22, isn't it?

There really isn't a simple fix for this. C++ does not provide a way to do unbuffered input from the keyboard. (Some compilers do provide functions that can do this, but they are not standard C++).

So you will have to find some other way to exit your loop. Maybe if the user hits enter without hitting any other keys first? You could do that by counting the number of chars returned before you see the \n, and exit if that number is 0.

I suspect it is not quite as it looks

and is always executing the break statement - hence ending

I suggest one of two things

1) always use {} on the if statement, even for one statement

2) use and else for the cout, not just let it drop through.

while (1) {

if(a=='\n') { break;}

else { cout<
}

getch();

It is always better to be explicit and clear rather than drop through

The key point of the while loop is that the loop might not ever run. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed. So it may be your while condition is not proper.

First off, you're using deprecated headers. Second, you should flush the IO buffers before reusing them and see what that does.

hello. i am writing a programme to keep entering number from user and giving it as output until the user presses enter key.

#include

#include

void main()

{

char a;

while(1)

{

cin.get(a);

if(a=='\n')

break;

cout<
}

getch();

}

it is not working properly. it takes input(for example 1), displays output(1) but then the programme ends. the loop is not working. it just accepts one character and displays it. please help