什么是'%'和格式说明符之间的数字在scanf函数是什么意思? [英] What does a number between '%' and format specifier mean in scanf ?

查看:305
本文介绍了什么是'%'和格式说明符之间的数字在scanf函数是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道的printf(),但我完全无能什么像%3D 可能意味着,如下面的code。

  scanf函数(%3D%3D,&安培; NUM1,&安培; NUM2);

要成为一般情况下,是什么之间的格式说明表示在scanf函数声明。

不是 scanf()的意味着简单地接收输入并将其存储在参数中指定的地址?


解决方案

您需要看的精美文档

基本上,和转换符之间的数字表示最大字段宽度。转换将停止已经处理了指定的字符数后。

这可以方便地削藩的数字序列为多个个体数,像这样:

 为const char *日期=20130426;
INT年,月,日;如果(sscanf的(日,4D%2D%2D%,&安培;今年,和放大器;当月,和天)== 3)
  打印(日期是%4D条所订%02d-%02D \\ N,年,月,日);

请注意格式字符串空白匹配的白色空间的序列中的输入(包括的的),所以上述作品即使输入的字符串(日期)不包含任何空格。在格式字符串中使用空格可以帮助使其更具可读性。

在回应你的标准输入评论,在的sscanf()函数不知道(或护理),其中它在操作字符串来源于,它只是一个字符串。所以,是的,你可以把它从标准输入读取数据,从一个文件,在其他程序中动态创建,收到通过网络,或任何其他方式。

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.

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

To be general, What does the number between % and format specifier indicate in a scanf statement.

Isn't scanf() meant simply to receive input and store it in the addresses specified in the argument?

解决方案

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. 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. 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.

这篇关于什么是'%'和格式说明符之间的数字在scanf函数是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆