Nirattasai
Nirattasai

Reputation: 3

Why my code show a false value of char variable

I write my code in C language but when I write like this

int main() 
{ 
   char one,two,three;
   int num=0;
   scanf("%d",&num);
   scanf("%c %c %c",&one,&two,&three);
   printf("%c %c %c",one,two,three);
}

When I input chars a b c that shows me

 a b

and does not show c

It happens when I input num. If I set a variable of num to be 3 it shows me

a b c

like my input

How to solve this?

Upvotes: 0

Views: 56

Answers (1)

TheWriter
TheWriter

Reputation: 256

When your first "scanf" processes, in addition to whatever number you're inputting you're also putting a newline character "/n" in as well. This is being read by your second "scanf" such that &one is your new line.

To fix this just change this line:

scanf("%c %c %c",&one,&two,&three);

To this:

scanf(" %c %c %c",&one,&two,&three);

The extra space in the second line will prevent the newline from being used by the second "scanf" statement.

Upvotes: 1

Related Questions