簡體   English   中英

用printf()與其他字符對正

[英]Right justifying with printf() with additional character

在我正在制作的表格中,我必須打印一個表示已證明費用正確的整數,這樣它總共可以容納六個字符,但是我還需要在數字前插入一個'$'字符。 有沒有一種方法,而無需創建一個新字符串,該字符串只是前面帶有$的整數?

這將打印[ $26] 括號只是用來顯示領先空間。
snprintf()將返回打印格式化字符串所需的字符數。
首先獲取寬度參數后, %*c將打印一個字符。

#include<stdio.h>
#include<stdlib.h>

int main ( ) {
    int cost = 26;

    printf ( "[%*c%d]\n", 6 - snprintf ( NULL, 0, "%d", cost), '$', cost);
    return 0;
}

我假設您正在執行正常的printf調用:

printf("%d", cost);

只是在前面添加它?

printf("$%d", cost);

此處提供更多幫助: https : //www.gnu.org/software/gawk/manual/html_node/Printf-Examples.html

暫無
暫無

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

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