簡體   English   中英

使用 printf 后如何打印 int 和帶空格的字符串?

[英]How to print an int and a string with spaces after using printf?

我通常使用printf("%-8d",a); 例如,在 integer 之后(包括)的 8 個空格。 我的代碼:

#include <stdio.h>
#include <string.h>
    
int main()
{
    int a = 10;
    char b = "Hello";
}

如何打印: '#10-Hello '有 16 個空格(8 個是 integer 和字符串,后面有 8 個空格)?

分兩步進行。 首先將數字和字符串與sprintf()組合,然后在 16 個字符的字段中打印結果字符串。

int a = 10;
char *b = "Hello";
char temp[20];
sprintf(temp, "#%d-%s", a, b);
printf("%-16s", temp);

一個制表符是 8 個空格,因此,您可以添加 \t\t 以下是打印您想要的內容的超級基本方法。

printf('#' + a + '-' + b + '\t\t');

我不太熟悉 C 的語法,所以它可能是:

printf('#', a, '-', b, '\t\t');

此外,如上一個答案中所述,“Hello”不是字符,而是字符數組或字符串。

#include <stdio.h>
#include <string.h>
    
int main()
{
    int a = 10;
    char b[] = "Hello";
    printf("#%d-%-17s",a,b);
}

這應該可以完成工作,根據需要調整間距

可以用 2 個printf()來做到這一點。 使用第一個的返回值知道它的打印長度,然后打印空間需要形成一個寬度為 16。不需要臨時緩沖區。

#include <assert.h>
#include <stdio.h>

int main(void) {
    int width = 16;
    int a = 10;
    char *b = "Hello"; // Use char *

    int len = printf("#%d-%s", a, b);
    assert(len <= width && len >= 0);
    printf("%*s", width - len, "");  // Print spaces
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM