1

Why does following program produce two output message at the same time, without asking for any input from the user???

#include <stdio.h>
#include <ctype.h>

int main(void) 
{
    char input;
    do {
        printf("Enter a single character: \n");
    scanf("%c", &input);
        printf("The ordinal value is %d. \n",input);    

        } while(input != '#'); 
    return 0;
}

The output is followings:

Enter a single character:
s
The ordinal value is 115.
Enter a single character:
The ordinal value is 10.
Enter a single character:
Jervis
  • 163
  • 5
  • 1
    If you want robust line-based user input, check out http://stackoverflow.com/questions/4023895/how-to-read-string-entered-by-user-in-c/4023921#4023921 – paxdiablo Mar 20 '11 at 01:52

2 Answers2

5

Terminal input is read line at a time unless you specify otherwise; scanf reads one character as specified, leaving the newline you typed afterward to send the line in the input buffer for the next pass of the loop. Consider reading input by lines and using sscanf() or similar to parse those lines.

geekosaur
  • 59,309
  • 11
  • 123
  • 114
  • 1
    +1 but if you read a full line of input (via `fgets`), you can just use `buffer[0]` to get the first character, rather than going through all the trouble of `sscanf`. Or, since we only want single characters, we can just use `fgetc` / `getc` / `getchar`. – Chris Lutz Mar 20 '11 at 01:37
  • Couldn't you just use scanf("%c\n",&input)? (Note the \n) – flight Mar 20 '11 at 02:14
0

Just insert getchar(); after your call to scanf. This will eat the newline. The suggestion to use scanf("%c\n", &input); seems sound, but I've never found it to work well; I wonder if anyone can tell me why?