[英]printf function string printout argument usage
I'm currently encountering this problem. 我目前遇到此问题。 I wanted to print out the #
as I defined in the code block below, thing is when I pass the printf
argument as printf("%*s\\n", x, BORDER)
, it prints out all the #
I defined at the beginning. 我想打印出来的#
我在下面的代码块中定义的,就是当我通过printf
参数作为printf("%*s\\n", x, BORDER)
,它打印出的所有#
我在定义开始。 However, when I write it as printf("%.*s\\n", x, BORDER)
then it prints out just as many #
as I wanted. 但是,当我将其写为printf("%.*s\\n", x, BORDER)
它会根据需要打印出#
。 Can someone tell me what's the difference that triggered this problem? 谁能告诉我引发此问题的区别是什么? I know width and precision stand an important role when it comes to float number printout, but this is string print out... 我知道宽度和精度在浮点数打印输出中起着重要作用,但这是字符串打印输出...
#include <stdio.h>
#include <string.h>
#define BORDER "############################################"
int main(void) {
char word[26];
int x;
scanf("%25s", word);
x = strlen(word) + 2;
printf("x = %d\n", x);
printf("%*s\n", x, BORDER);
printf("#%s#\n", word);
printf("%*s\n", x, BORDER);
return 0;
}
Here is the difference between the two syntaxes: 这是两种语法之间的区别:
The optional field width passed with %*s
specifies the minimum width to print for the string. 与%*s
一起传递的可选字段宽度指定了要为字符串打印的最小宽度。 If the string is shorter, extra spaces will be printed before the string. 如果字符串较短,则会在字符串之前打印多余的空格。
The optional precision passed with %.*s
specifies to maximum number of characters to print from the string argument. 由%.*s
传递的可选精度指定从字符串参数打印的最大字符数。
In your case, you want to limit the number of characters to print from the BORDER
string, so you should use the %.*s
format: 在您的情况下,您想限制从BORDER
字符串打印的字符数,因此您应该使用%.*s
格式:
printf("%.*s\n", x, BORDER);
Note however that this approach is not generic as you must keep to definition of BORDER
in sync with the array size. 但是请注意,这种方法不是通用的,因为您必须保持BORDER
定义与数组大小同步。
Here is a different approach: 这是另一种方法:
#include <stdio.h>
#include <string.h>
int main(void) {
char word[26];
if (scanf("%25s", word) == 1) {
int x = strlen(word) + 2;
char border[x + 2];
memset(border, '#', x);
border[x] = '\0';
printf("x = %d\n", x);
printf("%s\n#%s#\n%s\n", border, x, border);
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.