简体   繁体   English

scanf中'%'和格式说明符之间的数字是什么意思?

[英]What does a number between '%' and format specifier mean in scanf ?

I know the options used in format specifier for printf() , but I am totally clueless about what something like %3d could mean, as in the code below. 我知道printf()格式说明符中使用的选项,但是对于%3d含义我完全一无所知,如下面的代码所示。

scanf("%3d %3d",&num1,&num2);

To be general, What does the number between % and format specifier indicate in a scanf statement. 通常, %format specifier之间的数字在scanf语句中表示什么。

Isn't scanf() meant simply to receive input and store it in the addresses specified in the argument? scanf()并非仅意味着接收输入并将其存储在参数中指定的地址中吗?

You need to look at the fine documentation . 您需要查看详细的文档

Basically, a number between the % and the conversion specifier indicates the maximum field width. 基本上, %和转换说明符之间的数字表示最大字段宽度。 The conversion will stop after the specified number of characters has been processed. 在处理了指定数量的字符后,转换将停止。

This can be handy to "cut apart" a sequence of digits into multiple individual numbers, like so: 这样可以很方便地将数字序列“分割”为多个单独的数字,如下所示:

const char *date = "20130426";
int year, month, day;

if(sscanf(date, "%4d %2d %2d", &year, &month, &day) == 3)
  print("the date is %4d-%02d-%02d\n", year, month, day);

Note that whitespace in the format string matches any sequence of white space (including none ) in the input, so the above works even though the input string ( date ) doesn't contain any whitespace. 请注意,格式字符串中的空格匹配输入中的任何空格序列(包括none ),因此即使输入字符串( date )不包含任何空格,上述方法也可以工作。 Using whitespace in the format string can help make it more readable. 在格式字符串中使用空格有助于使其更具可读性。

In response to your stdin comment, the sscanf() function doesn't know (or care) where the string it operates upon comes from, it's just a string. 响应您的stdin注释, sscanf()函数不知道(或不在乎)其操作的字符串来自何处,它只是一个字符串。 So yes, you can call it on data read from stdin , from a file, created on the fly elsewhere in the program, received over the network, or any other way. 所以是的,您可以调用从stdin读取的数据,从文件读取的数据,在程序中其他地方动态创建的数据,通过网络接收的数据或任何其他方式调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM