0

Can someone please explain me why the scanf behaves differently in these two programs. I have prepared a sample test program to demo it.

Program Version 1

#include <stdio.h>

int main()
{
  int i;
  char c;
  for(i=0;i<4;i++)
  {
    scanf("%c",&c);
    printf("%c",c);
  }
return 0;
}

Program Version 2 (see scanf)

#include <stdio.h>

int main()
{
  int i;
  char c;
  for(i=0;i<4;i++)
  {
    scanf(" %c",&c); //The only difference is space
    printf("%c",c);
  }
return 0;
}

In program 1 I can enter
a
b
c
d

But in program 2 I can only enter
a
b

Why?

2 Answers2

1

the space in scanf means to skip whitespace characters at that point in the format string.

for the version without the space, the parsed characters are 'a', '\n', 'b', '\n'

for the version with the space, the parsed characters are 'a', skipped whitespace, 'b', skipped whitespace, 'c', skipped whitespace, 'd'

programmerjake
  • 1,794
  • 11
  • 15
-1

So going off of what programmerjake said, in the second program the white spaces are assigned to the i variable. a + space + b + space and then the loop stops.