[英]How can I print filled / unfilled square character using printf in c?
[英]How can I print multiple character with one printf?
我想使用printf
打印多個字符。 我到目前為止的方法是
#include <stdio.h>
int main()
{
printf("%*c\n", 10, '#');
return 0;
}
但這只會在#
之前打印9個空格。
我想這樣打印-
##########
我無法弄清楚該怎么做。 請幫我?
您不能使用這樣的printf
在Ansi C中打印重復的字符。我建議您使用這樣的循環-
#include <stdio.h>
int main()
{
int i;
for(i = 0; i < 10; i++) putchar('#');
return 0;
}
或者,如果您絕對不想使用循環,則可以執行以下操作:
#include <stdio.h>
int main()
{
char out[100];
memset(out, '#', 10);
out[10] = 0;
printf("%s", out);
return 0;
}
順便說一句,使用這樣的printf
也可以-
#include <stdio.h>
int main()
{
printf("%.*s", 10, "############################################");
return 0;
}
這將打印十個#字符,后跟換行符
char tenPounds[] = "##########";
printf( "%s\n", tenPounds);
我認為最好的方法是,如果要輸出的字符數上限是:
printf("%.*s", number_of_asterisks_to_be_printed,
"**********************************************************************");
我認為這也是最有效,最可移植的方法。
我正在“ C編程語言”書(練習1-13和1-14)中解決類似的問題。 首先,我自己的程序是對給定輸入中數字0到9的出現進行計數,並根據每個計數打印由'='條組成的水平直方圖。
為此,我創建了以下程序;
main() {
int c, ix, k;
int nDigit[10];
//Instantiate zero values for nDigits array
for(ix = 0; ix < 10; ix++) {
nDigit[ix] = 0;
}
//Pull in input, counting digit occurrences and
//incrementing the corresponding value in the nDigit array
while ((c = getchar()) != EOF) {
if (c >= '0' && c <= '9') {
++nDigit[c-'0'];
}
}
//For each digit value in the array, print that many
//'=' symbols, then a new line when completed
for (ix = 0; ix < 10; ix++) {
k = 0;
while (k <= nDigit[ix]) {
putchar('=');
k++;
}
printf("\n");
}
}
請注意,這是一項正在進行的工作。 正確的直方圖應包含坐標軸標簽,最重要的是,此程序不考慮零計數的數字。 如果輸入中包含五個1,但不包含0,則沒有視覺方法顯示我們沒有零。 盡管如此,用於打印多個符號的機制仍然有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.