-1

see the ouput image

What's the output of following code and why?

I am curious to know why c compiler shows the unusual output.

What happens behind the scene?

#include<stdio.h>
int main()
{
    char a,b,c;

    printf("Enter First char:");
    scanf("%c",&a);

    printf("Enter Second char:");
    scanf("%c",&b);

    printf("Enter Third char:");
    scanf("%c",&c);

    return 1;
}


Enter First char:a
Enter Second char:Enter Third char:c

see above output, its not taking 2nd input and directly asking third one!

Jerry Stratton
  • 3,287
  • 1
  • 22
  • 30
  • `// what's the output of following code and why ?`...did you atleast try running and understanding the output? – Sourav Ghosh Aug 09 '17 at 10:29
  • Well, what **is** the output? Run it and tell us (end especially tell us what confuses you about it) –  Aug 09 '17 at 10:30
  • 1
    What output do you expect and what output do you get, please edit your question and make that clear. – Jabberwocky Aug 09 '17 at 10:30
  • 1
    My guess it's about [this issue](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-buffer). – Some programmer dude Aug 09 '17 at 10:31
  • 1
    Possible duplicate of [scanf() leaves the new line char in buffer?](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-buffer). – Weather Vane Aug 09 '17 at 10:31
  • Is it about output of the program or "unusal output" of the compiler? Please be more precise. – Gerhardh Aug 09 '17 at 10:32
  • Enter First char:a Enter Second char:Enter Third char:c it shows the above output. i am not getting why? – Vikas Rathod Aug 09 '17 at 10:33
  • 1
    @VikasRathod please [edit] your question and put clarifications _there_. – Jabberwocky Aug 09 '17 at 10:33
  • ... as *text* not image please. You can read the duplicate question linked for an explanation and [solution](https://stackoverflow.com/a/5240807/4142924). – Weather Vane Aug 09 '17 at 10:37
  • 1
    Basic debug (printing a, b and c) would have answered this question before it was even posted... Possible duplicate of [scanf() leaves the new line char in buffer?](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-buffer) – John3136 Aug 09 '17 at 10:49

1 Answers1

0

First time you type 1 and hit Enter (Enter is interpreted as newline character)

The first scanf reads '1'.

The second scanf reads '\n'.

Then you type 2 and click Enter. The third scanf reads '2'.

Probably you need to read "%c " or " %c", since ' ' in format string skips all whitespaces.

user31264
  • 6,557
  • 3
  • 26
  • 40