![](/img/trans.png)
[英]How can I automatically add padding to bytes in a struct to fix register alignment in C?
[英]How can i fix an issue with padding in c?
我正在努力做到這一點,以便無論變量的長度(例如,最大長度為16
的char customer
)都將與標題Customer
對齊,如下所示:
# Customer Pizza Price Time
---------+---------+---------+---------+---------+---------+---------+---------+
01 Nick Hawaiian $15.99 15
---------+---------+---------+---------+---------+---------+---------+---------+
注意:我試圖以用戶輸入名稱變量的方式實現這一點,因此它的長度不同。
下面我在下面的代碼中遇到分段錯誤,不知道為什么:
void print_header(struct pizzeria *the_pizzeria) {
printf("# Customer Pizza Price Time\n");
printf("--------------------------------------------------------------------------------\n");
}
void print_order(struct order *the_order, int order_number, bool selected) {
int space_pizza = (26 - (strlen(the_order->customer)));
int space_cost = (26 - (strlen(the_order->pizza)));
int space_time = 5;
if (selected == true){
printf("%02d", order_number);
printf(">%4s", the_order->customer);
printf("%*s", space_pizza, the_order->pizza);
printf("$%*0.2f", space_cost, the_order->cost);
printf("%*20s\n", space_time, the_order->time);
}
else{
printf("%02d", order_number);
printf(" %4s", the_order->customer);
printf("%*s", space_pizza, the_order->pizza);
printf("$%*0.2f", space_cost, the_order->cost);
printf("%*20s\n", space_time, the_order->time);
}
}
我試圖跟隨Left-pad printf 和Rece Foc 的答案空格並由joepellier 編輯。
int space = 40;
printf("%*s", space, "Hello");
printf("%*d", space, 10);
printf("%*c", space, 'x');
在我嘗試這種方法之前,我這樣做了:
void print_order(struct order *the_order, int order_number, bool selected) {
if (selected == true){
printf("%02d >%4s %20s $%0.2f %20s\n", order_number, the_order->customer, the_order->pizza, the_order->cost, the_order->time);
}
else{
printf("%02d %4s %20s $%0.2f %20s\n", order_number, the_order->customer, the_order->pizza, the_order->cost, the_order->time);
}
}
我不確定我在這里做錯了什么,因為我不熟悉 c 和這種打印值的方式。
這是一個原型,您可以檢查並“調整”列寬並使用所需的數據源。
列寬應該很容易理解。 '%s' 定義中的前導 '-' 表示“在這么寬的字段中左對齊”。
請注意三元組“?:”,它將顯示“已選擇”的單個字符設置為空 SP 或 GT 符號。
void print( bool selected ) {
int ordNo = 42;
char selchar = selected ? '>' : ' ';
char *name = "Bob the Builder";
char *pizza = "Meat Lovers";
double cost = 25.75;
char *time = "23:30:05"; // midnight munchies
char *fmt = "%-4d %c%-35s%25s%13.2f%10s\n";
printf( fmt, ordNo, selchar, name, pizza, cost, time );
}
int main() {
print( false );
print( true );
return 0;
}
Output:
42 Bob the Builder Meat Lovers 25.75 23:30:05
42 >Bob the Builder Meat Lovers 25.75 23:30:05
對列寬進行微調,然后進行測試,然后進行更多微調,直到獲得您想要/需要的...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.