C: behaviour of getchar() after a print statement that ends in a whitespace???
Maybe a beginner's question but then I have been learning C for only two days...
How do I make getchar() skip a leading space? The situation I am looking is this: I print a prompt that ends in a space printf("Input: "); and then when I use getchar() to read the text that was typed after the prompt, it appears to process the trailing space as a leading space that belongs to the input. Could anyone explain why? And how can the space be skipped, preferably without inserting code that explicitly checks whether I'm reading the first character or not. I have already found out that I can skip such a space using scanf scanf (" %c", &ch); where the leading space in the format string eliminates leading spaces from the input string. That is the sort of thing I have in mind. |
Quote:
So, if, for example, you want to enter 'a', in fact you need to enter 'a', '\n'. So after the first call to 'getchar' you'll get 'a' (that's what you expect), but on the second call (suppose, you wanted to enter 'b') instead of 'b' you'll first get the '\n' you've entered after 'a', and only on the third call you'll get 'b', but again you'll have yet another '\n' in the buffer. Try 'fread' instead. |
Quote:
To observe how fread() acts buffered under ordinary circumstances, run this shell script: Code:
cat > 1.c <<EOD; rm -f 1; gcc -Wall -Werror 1.c -o 1; ./1 Code:
a prompt: x |
Quote:
|
We need termios for this. We really, really do.
Quote:
Code:
cat > 1.c <<EOD; rm -f 1; gcc -Wall -Werror 1.c -o 1; ./1 |
Thanks for your suggestions but I'm afraid I don't see how they answer my question. Like I said, the problem is that part of my output is being considered as input:
Code:
printf("Input: "); //print "Input: " prompt |
It does not take that trailing space (or at least I'm 99.99% sure that it does not)
Code:
#include <stdio.h> Code:
wim@btd-techweb01:~/progs/lq819120$ gcc -Wall lq819120.c -o lq819120 |
Hi Wim,
Terminal uses UTF.8. When I run your piece of code, I also get 41 hex so the problem must lie elsewhere. I think I'll need to take a better look at the code that was producing the problem. It seems quite likely that some method call before the printf statement leaves a new line in the buffer. |
All times are GMT -5. The time now is 11:07 PM. |