Whitespace before %c specification in the format s

2019-01-15 21:51发布

This question already has an answer here:

When I don't include whitespace between %d and %c specification in the format string of scanf function in the following program, and give input during run-time as "4 h", then the output is "Integer = 4 and Character= .

How exactly variable "c" takes the input in this case and what difference does it make if i include a whitespace between %d and %c specification ?

#include<stdio.h>
main()
{
char c;
int i;
printf("Enter an Integer and a character : \n");
scanf("%d %c",&i,&c);
printf("Integer = %d and Character = %c\n",i,c);
getch();
}

2条回答
Rolldiameter
2楼-- · 2019-01-15 22:10

A space before %c specifier in scanf instruct it to skip any number of white-spaces. In other words, read from standard input until and unless a non-white-space character or keyboard interrupt is found.

查看更多
We Are One
3楼-- · 2019-01-15 22:21

If you read the specification for scanf() carefully, most format specifiers skip leading white space. In Standard C, there are three that do not:

  • %n — how many characters have been processed up to this point
  • %[…] — scan sets
  • %c — read a character.

(POSIX adds a fourth, %C, which is equivalent to %lc.)

Input white-space characters (as specified by isspace) shall be skipped, unless the conversion specification includes a [, c, C, or n conversion specifier.

Adding the space between %d and %c means that optional white space is skipped after the integer is read and before the (not white space) character is read.

查看更多
登录 后发表回答