c - 使用 C 的 sprintf 将文本文件格式化为列

标签 c for-loop

我有一个基本的文本文件,我将我的程序指向要运行的文件,其中逐行显示数字,例如:

3
30
300
3000
30000
300000
3000000
30000000
300000000
-3
-30
-300
-3000
-30000
-300000
-3000000
-30000000
-300000000

and I need to print them out into evenly spaced columns and I want them to fit into 40 characters (4 columns wide). I want to use the sprintf function to do this. So basically print each number out plus 2 spaces for formatting and fit within 40 characters total. So far this is what I have.

int main(int argc, char *argv[]){

    int a, b, num[1000], nums = 0;
    char str[40];
    FILE *pt;
    int col, max, w;

    if(argc < 2){
      printf("Usage %s <No Files>\n", argv[0]);
      return 1;
    }

   if((pt = fopen(argv[1], "r")) == NULL){
     printf("Unable to open %s for reading.\n", argv[1]);
     return 1;
   }

   while(fscanf(pt, "%d", &b) == 1){
     num[nums++] = b;
   }

   w = sprintf(str, "%*d", num[a]);

   if(max < w){
     col = 40 / (max + 2);
     printf("%d  %d\n", w, num[a]);
   }

   return 0;

 }

当我将它指向上面提到的文本文件时,我只是得到了垃圾。有什么建议吗?

最佳答案

要在宽度为 10 个字符的 4 列中打印 N 个数字,请在循环内使用 printf("%10d"),在每第 4 个之后添加新行 (\n)打印,例如:

for (int i = 1; i <= nums; i++)
{
    printf("%10d", num[i-1]); // or printf("%-10d", num[i-1]);
    if (i % 4 == 0)
        printf("\n"); // or putchar ('\n')
}

%-10d 格式更改对齐方式的 - 符号。

如您所见,此处未使用 sprinf,我对每个数字使用 printf 以在屏幕(标准输出)上打印值。

更新:

如果你想找到列的最佳宽度,并将其用于输出,例如使用最大数字中的位数(让它成为 maxValue 数组 num 中找到的整数值),你可以找到所需的最小位数(让它为 minWidth),例如:

char buff[20] = {0};
int minWidth = strlen(_itoa(maxValue,buff,10));

然后像这样改变打印循环:

for (int i = 1; i <= nums; i++)
{
    printf("%*d", minWidth + 1, num[i - 1]);
    if (i % 4 == 0) putchar('\n');
}

这里vlaue minWidth + 1将被用在格式说明符%*d中,而不是*,而+1 用于一个空格内各列之间的最小分隔(当然也可以有2个或3个)。

最后,计算出列宽后,您可以找到屏幕的列数,并使用此值开始新行,例如:

const int screenWidth = 80;
int colWidth = minWidth + 2; // here 2 is added for minimum separation of columns
int colNum = screenWidth / colWidth;

for (int i = 1; i <= nums; i++)
{
    printf("%*d", colWidth, num[i - 1]);
    if ( !(i % colNum) ) putchar('\n'); // !(i % colNum) is the same to i % colNum == 0
}

关于c - 使用 C 的 sprintf 将文本文件格式化为列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45181071/

相关文章:

java - for循环并不是每次循环时都加1

c - 如何修改 C 程序以便 gprof 可以分析它?

c++ - std::list<std::reference_wrapper<T>> 的基于概念限制范围的 for 循环

python : how to make 1-D array from 2-D array

list - 如何在 Scala 中保持表达式的函数式风格

结合for循环和if语句的Pythonic方式

c - 获取 GCC 错误 : "sys/memfd.h: No such file or directory"

C - 通过读取 csv 文件获取调试断言失败错误

c# - 在结构中使用 boolean 值的一些 P/Invoke C# 到 C 编码问题

c - 是否有 memset() 接受大于 char 的整数?