C语言 scanf 中的 %2d 是什么
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13913848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
what is the %2d in scanf
提问by Ashwin
I know the meaning of this statement
我知道这句话的意思
scanf("%d",&x);
But what does this statement do
但是这个语句有什么作用
scanf("%2d",&x);
I tried searching for this, but could not find an answer. I want to know what happens internally also.
我试图寻找这个,但找不到答案。我也想知道内部发生了什么。
回答by user327843
That's two digits number:
这是两位数:
int n = 0;
scanf ("%2d", &n);
printf ("-> %d\n", n);
12 -> 12
12 -> 12
88657 -> 88
88657 -> 88
回答by Roberto Fajardo
The number right after the '%' sign and right before the type of data you wish to read represents the maximum size of that specific type of data.
'%' 符号之后和您希望读取的数据类型之前的数字表示该特定数据类型的最大大小。
As you are reading an integer (%2d), it will only allow an integer up to twodigits long. If you were to read a 50 characters long array, you should use %49s (leaving one for the null terminating byte). It is the same idea.
当你正在阅读的整数(%2D)时,将只允许一个整数高达2个位数。如果要读取 50 个字符长的数组,则应使用 %49s(为空终止字节留一个)。这是同样的想法。
int number = 0;
scanf("%2d", &number);
printf("%d", number);
If the user passed 21 for the scanf() function, the number 21 would be stored in the variable number. If the user passed something longer than 21, i.e. 987, only the first 2 digits would be stored - 98.
如果用户为 scanf() 函数传递了 21,那么数字 21 将存储在变量 number 中。如果用户传递的数字大于 21,即 987,则只会存储前 2 位数字 - 98。

