2
#include <stdio.h>

int main(void) {
   char ch,ch1;
   scanf("%c",&ch);/*input ab here*/
   scanf("%c",&ch1);
   printf("%c %c",ch,ch1);
   return 0;
}

Why this produces a b as output. We don't enter any input for second variable but it still got assigned. Could anyone explain the behavior.

You can check the output here if you want.

3
  • 5
    "%c" scans one byte of input, which consumes a, and b is still in the input stream when the second scanf() gets called. That's just how scanf() works. Commented Jul 17, 2014 at 7:22
  • You don't handle the newline, %c doesn't skip blank lines. Commented Jul 17, 2014 at 7:23
  • Are you trying to put multiple characters in a char? That's what the question title looks like. I haven't messed around with <stdio.h> because I use C++ and <iostream>, but %c looks like, at a glance, the syntax to represent a char in <stdio.h>. Correct me if I'm wrong, please. :) Commented Jul 17, 2014 at 7:31

4 Answers 4

2

We don't enter any input for second variable

That's not true, "%c" in scanf reads one character, after it processes the input a, the "%c" in the next scanf then reads the next input character b.

Sign up to request clarification or add additional context in comments.

2 Comments

But dont you think scanf ends the input after encountering a newline character. Here We enter the new line character after typing 'ab'. Then how come b goes to second variable.
@anujpradhan Add another scanf("%c",&ch2); after the second, you'll see the newline character in ch2.
2

Because you entered 2 characters in the 1st input while the program expects just 1: the 2nd is pending until the next call to scanf

Comments

0

this may get you rid of the situation

scanf("%c",&ch);/*input ab here*/
fflush(stdin);
scanf("%c",&ch1);

EDIT Your actual problem is that ch1 is being assigned with the newline character(or the space as tried in IDEONE simulator)

To check that : enter your values without any separation.

1 Comment

still the same problem.
0

Scanf can do multiple scans:

char a1, a2, a3, a4;
scanf("%c%c%c%c", &a1, &a2, &a3, &a4);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.