格式化數據比科學更接近藝術。
考慮到項目壽命期間的字段寬度將會改變(更可能增長)。
便於維護的郵政編碼。第一次絕對不對。性能不是那麼關鍵,因爲輸出無論如何都是CPU週期的一個漏洞。
重複使用格式。
字符串字面量避免fprintf()
,改用fputs()
。
RTFM fprintf()
並讓最小寬度指定符爲您的朋友。
小心一個格式的孤獨"%"
。應該"%%"
第一次嘗試:
double loan, rate, monthlyPayment, interestEarned;
loan = interestEarned = monthlyPayment = 12345.78;
rate = 999.99;
int years = 30;
// Let us assume interesting part of the table is 10 wide
// 10 =
// .max_width
const char *fdash = "%s%.10s%s";
// space, 8 char, space
// - left justify
// min_width.max_width
const char *ftext = "%s %-8.8s %s";
// $, 8 width with 2 dec. places, space
// width.precision
const char *fcash = "%s$%8.2f %s";
// space, 7 width, %, space
// width.precision
const char *fperc = "%s %7.2f%% %s";
// space, 8 wide, space
// width
const char *fyear = "%s %8d %s";
const char *bar = "=================================="; // extra long
fputs("\n", stdout);
printf(fdash, "#==============================", bar , "#\n");
printf(ftext, "| Description |", "Input Data" , "|\n");
printf(fdash, "|==============================", bar , "|\n");
printf(fcash, "| Loan amount |", loan , "|\n");
printf(fperc, "| Yearly interest rate |", rate , "|\n");
printf(fyear, "| Number of years |", years , "|\n");
printf(fdash, "|==============================", bar , "|\n");
printf(ftext, "| Payment Details |", "Results" , "|\n");
printf(fdash, "|==============================", bar , "|\n");
printf(fcash, "| The monthly payment will be |", monthlyPayment, "|\n");
printf(fcash, "| Interest paid |", interestEarned, "|\n");
printf(fdash, "#==============================", bar , "#\n");
fputs("\n", stdout);
輸出:字段太小"Input Data"
。修復留給用戶。
#========================================#
| Description | Input Da |
|========================================|
| Loan amount |$12345.78 |
| Yearly interest rate | 999.99% |
| Number of years | 30 |
|========================================|
| Payment Details | Results |
|========================================|
| The monthly payment will be |$12345.78 |
| Interest paid |$12345.78 |
#========================================#
將(6.2,5.2)變爲8.2,不需要3個不同的值。將'%d'更改爲%8d – chux
...和'%8d'。第一個數字是總場寬。 (哦@chux已經編輯了他的評論) –
也是那樣懸而未決''%| \ n「' - >'」%% | \ n「' – chux