-1

I'm struggling on a question proving scanf() and getchar() can both retrieve a character from the input.

However, when I try to put them inside the same program, only the first function is running properly. The latter is discarded completely.

#include <stdio.h>

char letter;
int main()
{
    printf("I'm waiting for a character: ");
    letter = getchar();
    printf("\nNo, %c is not the character I want.\nTry again.\n\n",letter);

    printf("I'm waiting for a different character: ");
    scanf("%c",&letter);
    printf("Yes, %c is the one I'm thinking of!\n",letter);
    return(0);
}

output

I have tried switching the places of those two functions but it is of no use. Can someone help me find the issue and provide a way to fix this? The only requirement is that the program takes input twice, once by the getchar() function and once via scanf()

1 Answers1

0

The second read attempt just reads whitespace (the end of line character, since you pressed enter after the first letter). Simply replace it with this:

scanf(" %c", &letter);

The space before % will tell scanf to read the next non-whitespace character.

DarkAtom
  • 2,589
  • 1
  • 11
  • 27