Question

Through my search for a solution I found this question. Which made me think and make some experiments:

Case 1

#include<stdio.h>
main()
{ char a;
   //some code
  scanf("%c",&a);
   /*This code might not be evaluated(missed) 
    sometimes*/
  //This is how it is solved
  scanf("  %c",&a);
  //the rest of code
  }

case 2

#include<stdio.h>
main()
{ int a;
   //some code
  scanf(" %d ",&a);
  //this one will take 2 numbers instead of one
  //the rest of code
  } 

I don't know much about c language so it would be appreciated if someone explains these results to me.(I'm using turbo c++ if it matters.)

Was it helpful?

Solution

A couple of general notes:

  1. If you want to ask questions about C it would be beneficial for you to read about how the functions work. There is a lot of documentation available online for scanf() for example.
  2. It's always better when you can give full compile-able examples rather than //some code

So in your first case the example would be:

char a, b;
scanf("%c", &a);
scanf("%c", &b); // this one will be "missed"

The reason is that when you enter a character in to stdin you're getting two characters really, what was typed plus an invisible newline character ('\n'). So really the second scanf isn't "missed" it's just picking up a character that doesn't have an ASCII representation.

If you printed these with:

printf("%c %d\n%c%d\n", a, a, b, b);

you would see:

>> ./my_prog
>> a
>> a 97

   10

Because you entered "a\n" and the two scanf's read first the "a" then the "\n" respectively.

Using a scanf with a space before it:

scanf(" %c", &b); // this one will work instead

Will tell the scanf that any white space characters (including the newline '\n') left on stdin should be ignored.


In your second case, it's not looking for 2 numbers, it's looking for a number and a white space character. scanf(" %d ", &a) says "ignore any white space, then look for a decimal number, then look for white space". However once the variable (a) is filled it stops reading, because this is how scanf works:

A directive composed of one or more white-space characters shall be executed by reading input until no more valid input can be read, or up to the first byte which is not a white-space character, which remains unread.

So it's not really looking for another number, you can type anything at this point and it will be happy because it's just looking for another white space character to be input. So this:

scanf(" %d ", &a);

could be satisfied by this input:

>> 5
   f

First the "%d" matches the 5, then the newline following the f matches the " "

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top