1

I am doing a simple example related to scanf()

int a, b;
printf("Please enter int a:\n);
scanf("%d",&a);//line 1
printf("Please enter int b:\n);
scanf("%d",&b);//line 2

I run this code at a I put 45, and b 78, so the input buffer looks like this: 45\n78\n, line1 takes 45 ignores \n, and line2 ignores \n takes 78 and ignores \n

char ch, ch2;
printf("Please enter char ch:\n);
scanf("%c",&ch);//line3
printf("Please enter char ch2:\n);
scanf("%c",&ch2);//line4

I debugged this code and I thought of putting 'a' in ch, and 'b' in ch2, so the input buffer will look like this: a\nb\n, line3 takes 'a' ignores \n and line4 ignores \n takes 'b' and ignores \n

I thought this would happen, but when I debugged it line3 takes 'a', and line4 reads \n and stores it.

I don't understand I thought scanf() is supposed to ignore whitespace characters.

as you can see here http://www.cplusplus.com/reference/cstdio/scanf/

Embedded_Dude
  • 227
  • 3
  • 9

1 Answers1

3

From man scanf:

%c

Matches a sequence of characters whose length is specified by the maximum field width (default 1); the next pointer must be a pointer to char, and there must be enough room for all the characters (no terminating null byte is added). The usual skip of leading white space is suppressed. To skip white space first, use an explicit space in the format.

Community
  • 1
  • 1
Mathieu
  • 8,840
  • 7
  • 32
  • 45