-3

My code:

#include "stdio.h"
main() {
    char a,b;
    a=getchar();
    b=getchar();

    putchar(a);
    putchar('\n');
    putchar(b);
}

getchar() requires user to enter a character and then press enter to assign it to the variable. I expected the program letting me enter the character twice, each time finished by pressing enter. But I was only able to enter one character string and the program will automatically read the first two characters and assign them to each variable. What's the problem?

Rohan Kumar
  • 5,427
  • 8
  • 25
  • 40
AtlasRE
  • 1
  • 1
  • 1
    the problem is that you type character + enter. The first `getchar()` reads the character, the second the newline. Many similar questions here, btw. – Ingo Leonhardt Sep 21 '17 at 14:30
  • Each time you hit ENTER you do enter a character (`\n`). So you are actually entering 2 chars at a time. – P.P Sep 21 '17 at 14:30
  • 1
    Aside: `#include"stdio.h" main() { char a,b; ...` should be `#include int main(void) { int a,b; ...` – Weather Vane Sep 21 '17 at 14:32
  • `getchar()` reads from the input buffer when `Enter` is pressed. So if you type `a` then `b` then `Enter`, the output will be `a` and `b`. – Weather Vane Sep 21 '17 at 14:40

1 Answers1

-1

getchar() requires user to enter a character and then press enter to assign it to the variable.

No. getchar() accepts single character as input . Even enter \n is considered as a single character to getchar(). So when you enter a character it would be the input for first getchar() and enter '\n' will be the input for second getchar().

Ex:

When you press a it would be read by first getchar(), after which if u hit enter '\n' it would be considered as input for second getchar().

Nerdy
  • 1,016
  • 2
  • 11
  • 27