什么是 scanf("%*s") 和 scanf("%*d") 格式标识符? [英] What are scanf("%*s") and scanf("%*d") format identifiers?
问题描述
scanf() 中"%*"
格式的实际用途是什么.如果这种格式存在,那么它背后一定有某种目的.下面的程序给出了奇怪的输出.
What is the practical use of the formats "%*"
in scanf(). If this format exists, there has to be some purpose behind it. The following program gives weird output.
#include<stdio.h>
int main()
{
int i;
char str[1024];
printf("Enter text: ");
scanf("%*s", &str);
printf("%s
", str);
printf("Enter interger: ");
scanf("%*d", &i);
printf("%d
", i);
return 0;
}
输出:
manav@workstation:~$ gcc -Wall -pedantic d.c
d.c: In function ‘main’:
d.c:8: warning: too many arguments for format
d.c:12: warning: too many arguments for format
manav@manav-workstation:~$ ./a.out
Enter text: manav
D
Enter interger: 12345
372
manav@workstation:~$
推荐答案
对于 printf,* 允许您通过额外参数指定最小字段宽度,例如printf("%*d", 4, 100);
指定字段宽度为 4.字段宽度为 4 表示如果打印一个数字少于 4 个字符,则打印空格字符,直到字段宽度已填充.如果数字占用的空间超过指定的字段宽度,则数字按原样打印,不截断.
For printf, the * allows you to specify the minimum field width through an extra parameter, e.g. printf("%*d", 4, 100);
specifies a field width of 4. A field width of 4 means that if a number takes less than 4 characters to print, space characters are printed until the field width is filled. If the number takes up more space than the specified field width, the number is printed as-is with no truncation.
对于 scanf
,* 表示该字段将被读取但被忽略,例如scanf("%*d %d", &i)
对于输入 "12 34" 将忽略 12 并将 34 读入整数 i.
For scanf
, the * indicates that the field is to be read but ignored, so that e.g. scanf("%*d %d", &i)
for the input "12 34" will ignore 12 and read 34 into the integer i.
这篇关于什么是 scanf("%*s") 和 scanf("%*d") 格式标识符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!