Hello. So I've been doing some C today... and wondering how the heck do I get a single char in a loop? I've used getchar and scanf, they both read my newline and skip prompt on 2nd iteration.
Code: #include <stdio.h> main() { char c; while(1) { printf("Enter a char: "); c = getchar(); printf("%d\n", c); } }
Its doing exactly the correct thing getting one character at a time. The problem is that you have two sources going to the same device. Keyboard input is going to terminal. Output from your program is also going to the terminal. Simple solution: Run the command in one terminal and look at the output of the program in another terminal. How: Execute program and output to a file: ./a.out > PLOP tail the file from another terminal tail -f PLOP PS. You need the -f. It makes tail wait for more input to the file.
Re: Properly get a single character. « Reply #6 on: September 17, 2008, 08:38:32 AM » Quote from: myork on September 17, 2008, 08:14:38 AM The problem is that you have two sources going to the same device. Are you sure? I think the problem is the newline stays in buffer, and is read up on next getchar() call. I think reading the stream until newline is a simpler solution: Code: int myGetChar() { int c, dummy; c = dummy = getchar(); while(dummy != '\n' && dummy != EOF) dummy = getchar(); return c; }