2017-02-20 194 views
1

我目前遇到此问题。我想打印出#,就像我在下面的代码块中定义的那样,事情是当我通过printf参数作为printf("%*s\n", x, BORDER)时,它打印出我在开头定义的所有#。但是,当我将它编写为printf("%.*s\n", x, BORDER)时,它将打印出与我想要的一样多的#。有人能告诉我触发这个问题的区别是什么?我知道宽度和精度站在了重要的作用,当涉及到浮点数打印,但这是字符串打印出来......printf函数字符串打印输出参数用法

#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; 
} 
+3

时间阅读手册页?它涉及很多。手册页应始终是您的第一个参考。 –

+0

字符串的指定*宽度*和指定*精度*之间的差异。请参阅[printf' **](http://en.cppreference.com/w/c/io/fprintf)的文档,并仔细阅读。使用's'时,*“精度指定要写入的最大字节数”。* – WhozCraig

+0

是阅读手册页。它会特别详细地告诉您:“...或s和S转换的字符串打印的最大字符数” – kaylum

回答

2

下面是两种语法之间的区别:

  • 的可选字段宽度通过%*s指定字符串打印的最小宽度。如果字符串较短,则会在字符串之前打印多余的空格。

  • 可选精度通过%.*s指定从字符串参数打印的最大字符数。

在你的情况,你想限制字符从BORDER字符串打印的数量,所以你应该使用%.*s格式:

printf("%.*s\n", x, BORDER); 

不过请注意,这种做法是不通用的您必须保持与数组大小同步的BORDER的定义。

这是一种不同的方法:

#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; 
}