Question

Can some one explain me why I see a double input of the printf() function the while loop:

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

int main(){
    int x = 0;

    while ( x != 'q'){

    printf("\nEnter a letter:");

    x=getchar();
    printf("%c\n", x);
    if( isalpha(x) )
      printf( "You entered a letter of the alphabet\n" );
    if( isdigit(x) )
      printf( "You entered the digit %c\n", x);
    }   
    return 0;
}

The output of the code in Debian Squeeze (gcc version 4.4.5 (Debian 4.4.5-8)) is:

Enter a letter:1
1
You entered the digit 1

Enter a letter: // why is the first one appearing ???


Enter a letter:2
2
You entered the digit 2
Was it helpful?

Solution

The first one reads the line terminator character you entered when hitting Enter after 1 (the line terminator will remain in the input buffer).

You can verify this by adding an else branch:

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

int main()
{
  int x = 0;
  while ( x != 'q')
  {
    printf("\nEnter a letter:");
    x = getchar();
    printf("%c\n", x);
    if( isalpha(x) )
      printf( "You entered a letter of the alphabet\n" );
    else if( isdigit(x) )
      printf( "You entered the digit %c\n", x);
    else
      printf("Neither letter, nor digit: %02X\n", x);
  }
  return 0;
}

The output:

Enter a letter:1
1
You entered the digit 1

Enter a letter:

Neither letter, nor digit: 0A

Enter a letter:2

The byte 0A is the line-feed character.

OTHER TIPS

The second time through the loop, getchar() is getting the Enter after the first char you entered.

You could do something like

while ((c = getchar()) != EOF && c != '\n') {} /* eat the rest of the line */

to get rid of everything up to and including the next Enter after getting a char and before asking for another.

If you want to check characters as you enter a slightly advanced technique would be to change stdin's behavior to raw mode.Then as soon as the user hits a char you get that in your variable. Check this for some start

Use CTRL + D to get the functionality of the newline character without its side effect.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top