简体   繁体   English

如何使用C在终端上打印格式化输出?

[英]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.我已经用 C 编写了一个图书馆系统的代码。我想在 Linux 的终端上以下列方式显示输出。 I tried with "\\t" but the output gets disturbed when the string size varies.我尝试使用 "\\t" 但当字符串大小变化时输出会受到干扰。 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.我尝试使用 "\\t" 打印它,但是当书或作者的字符串长度变小或变大时,格式会受到干扰。 Can somebody help me with this??有人可以帮我解决这个问题吗??

Print with fixed character size.以固定字符大小打印。 Here it is 7,11 and 10 for columns.这里的列是 7,11 和 10。 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.不是 linux 用户(希望我们谈论的是等宽输出),但我的经验是tab通常具有可配置的大小,因此如果您格式化为6字符的长度而有人有 4 个字符的tab ,结果会很糟糕。 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计算item长度
  4. add missing spaces (before or after) to line or itemlineitem添加缺失的空格(之前或之后)
  5. add item to lineitem添加到line
  6. loop #2 for all items所有项目的循环#2
  7. output line输出line
  8. loop #1 for all lines所有行的循环#1

use printf like this :像这样使用 printf :

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

(the - in %-25s is use to left-justifies your text) (%-25s 中的 - 用于左对齐文本)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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