tags:

views:

76

answers:

3

I'm it really sure how to explain this question but i'll give it a try.

I have this line of code in my program:

scanf (" %c", &character);

Notice the space before %c. This is supposed to keep the scanf from interpreting the last ENTER key as a character. This works, however after this line and its resulting printf output the program will not continue to execute until I provide another character and then press the ENTER key. After that it ignore all scanf and prints all printf output with the absence of any user input. Does that make sense. Im new to C so im sure im missing something simple but I couldn't find any solutions.

Thanks!

A: 

Try this:

scanf ("\n%c", &character);

It should "consume" the \n character in buffer and then wait for a new char.

Pablo Santa Cruz
That still doesn't work. Same problem.
Postulate
Can you post some more lines of code?
Pablo Santa Cruz
There is no difference between `" %c"` and `"\n%c"` as far as `scanf()` goes - whitespace is just whitespace.
caf
+1  A: 

The standard input is buffered.

Your code will not see the buffer until it (the standard input) is flushed.
This happens when the buffer becomes full or the '\n' (Enter Key) is inserted.

Because scanf() is a blocking I/O call. The application will wait for input (indefinitely). Thus making the code look like it has stalled.

IMHO

You should not try and interpret what has happend behind you in previous parts of the code. This will couple your code to other input that you may have no control over. Your input should read everything it need to and no more.

For example: If you ask the user to enter a character then hit enter. You should remove the character then enter from the input stream. You should not expect the next user of the stream to tidy up for you (or compensate for your code).

printf("Enter (Y/N)\n");
scanf("%c", &character);
scanf("%*[^\n]"); // Ignore everything to the end of line.
                   // Assuming you have told the user you will ignore
                   // extraneous characters. The next input should now
                   // expect only what they need.
Martin York
I don't think you mean `sscanf()` there... and that won't actually eat the newline itself.
caf
A: 

In your previous scanf call, use something like scanf("%c\n", &character); to eat the newline as it is entered. This is typically less error-prone than waiting to handle it the next time you need input.

bta