-2

This easy code in C won't work, and I don't get it why. If I read only "n", or only "ch" separately, it works, otherwise if I try to read them both, it won't let me read "ch". What happens and how could I make it work?

#include <stdio.h>

int main()
{
    int n;
    char ch;

    printf("n=");
    scanf("%d",&n);
    printf("ch="); //when i press Build and Run it won't let me read "ch"??? why?
    scanf("%c",&ch);
    return 0;
}
meiznub
  • 75
  • 5

1 Answers1

2

When you read in a number using %d, a newline is left in the input buffer. When you then read a character with %c, it reads that newline immediately so you don't get prompted for more input.

Unlike the %d format specifier, which discards any leading whitespace, the %c format specifier does not.

Add a leading space before %c to consume any leftover whitespace:

scanf(" %c",&ch);
dbush
  • 205,898
  • 23
  • 218
  • 273