Vishal Patil
Vishal Patil

Reputation: 305

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- enter image description here

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??

Upvotes: 2

Views: 1696

Answers (3)

Spektre
Spektre

Reputation: 51933

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

Upvotes: 0

user6065366
user6065366

Reputation:

use printf like this :

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

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

Upvotes: 1

Lahiru Jayakody
Lahiru Jayakody

Reputation: 5410

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);

Upvotes: 1

Related Questions