简体   繁体   中英

how to print formatted output on terminal using C?

I have written a code for a Library system in C. And I want to show the output in following manner on terminal on Linux. I tried with "\\t" but the output gets disturbed when the string size varies. I want to print it in fixed manner no matter what string size comes.

I want to print output like below- 在此处输入图片说明

I tried to print this using "\\t" but the format gets disturbed when the string length of book or author gets smaller or larger. Can somebody help me with this??

Print with fixed character size. Here it is 7,11 and 10 for columns. Refer this for more details this

printf("Column1    Column2   Column3\n");
printf("%7d%11s%10d\n", 100, "String1", 9348);
printf("%7d%11s%10d\n", 23, "String2", 214);

not a linux user (hope we are talking about monospace output) but my experienceis that tab has usually configurable size so if you format for 6 character length and someone have 4 character tab the result will be bad. The safest is to use spaces. You can use formated output like:

printf("float number: 8.3%f",7.56);

But that is not always a good choice for example sometimes negative sign mess up things ...

I usually handle such formatting my self with use of string variables:

  1. line = ""
  2. item = "single unformated text value"
  3. compute length of item
  4. add missing spaces (before or after) to line or item
  5. add item to line
  6. loop #2 for all items
  7. output line
  8. loop #1 for all lines

use printf like this :

printf("%-25s|\n", "a string");
printf("%-25s|\n", "another string");

(the - in %-25s is use to left-justifies your text)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM