如何在 C 語言中使用對齊方式對輸出進行對齊?
透過在 printf 語句中使用對齊方式 ,我們可以在任何格式下排列資料。
右對齊
若要實現右對齊,請在 %s 字元中的寬度值前插入減號。
printf("%-15s",text);程式 1
讓我們舉一個使用對齊方式按行和按列列印資料的示例。
#include<stdio.h>
int main(){
char a[20] = "Names", b[20]="amount to be paid";
char a1[20] = "Bhanu", b1[20]="Hari",c1[20]="Lucky",d1[20]="Puppy";
int a2=200,b2=400,c2=250,d2=460;
printf("%-15s %-15s
", a, b);
printf("%-15s %-15d
", a1,a2);
printf("%-15s %-15d
", b1,b2);
printf("%-15s %-15d
", c1, c2);
printf("%-15s %-15d
", d1, d2);
return 0;
}輸出
Names amount to be paid Bhanu 200 Hari 400 Lucky 250 Puppy 460
程式 2
透過更改對齊方式考慮同一個示例 −
#include<stdio.h>
int main(){
char a[20] = "Names", b[20]="amount to be paid";
char a1[20] = "Bhanu", b1[20]="Hari",c1[20]="Lucky",d1[20]="Puppy";
int a2=200,b2=400,c2=250,d2=460;
printf("%2s %2s
", a, b);
printf("%5s %5d
", a1,a2);
printf("%2s %2d
", b1,b2);
printf("%5s %5d
", c1, c2);
printf("%2s %2d
", d1, d2);
return 0;
}輸出
Names amount to be paid Bhanu 200 Hari 400 Lucky 250 Puppy 460 Note: Alignment is note in proper if we not use correct justification
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP