我想编写一个程序,它将打开一个csv文件并在txt文件中创建其可视化。
我的意思是:
输入: (这是CSV文件(
apple;orange;strawberry
car;warsaw;ansi
在 TXT 文件中输出
apple|orange|strawberry
car |warsaw| ansi
这个想法是整个列的宽度应该调整为其中最长的表达式
我的程序中的输出
苹果|橙子|草莓
|汽车|华沙|安西
|
我有太多的分隔符,它们不对齐
我的代码:
#include <stdio.h>
#include <string.h>
#include <string.h>
#define MAXLINE 1000
int how_many_delimiter(char array[]);
int main(void)
{
FILE *f,*f_2;
int *size_of_column, counter, hmd, min;
char corrector[] = ";", rows[MAXLINE], *clipboard;
f = fopen("ex-5.csv", "r");
f_2 = fopen("wynik.txt", "w");
fgets(rows, MAXLINE, f);
hmd = how_many_delimiter(rows);
size_of_column = (int*)calloc(hmd,sizeof(int));
min=10;
while(fgets(rows, MAXLINE, f))
{
clipboard = strtok(rows, corrector);
counter=0;
if(strlen(clipboard)>size_of_column[counter])
{
size_of_column[counter] = strlen(clipboard);
}
while(clipboard!=NULL)
{
if(strlen(clipboard)>size_of_column[counter])
{
size_of_column[counter] = strlen(clipboard);
}
clipboard = strtok(NULL,corrector);
counter++;
}
}
fclose(f);
f = fopen("ex-5.csv", "r");
while(fgets(rows, MAXLINE, f))
{
clipboard = strtok(rows, corrector);
counter=0;
while(clipboard!=NULL)
{
fprintf(f_2,"%-*s|",size_of_column[counter], clipboard);
clipboard = strtok(NULL,corrector);
counter++;
}
}
fclose(f);
fclose(f_2);
return 0;
}
int how_many_delimiter(char array[])
{
int counter, i;
i = 0;
counter = 1;
while(array[i]!='n'&& array[i]!=EOF)
{
if(array[i]==';') counter++;
i++;
}
return counter;
}
执行此操作的步骤(使用"%*s", width
方法的替代方法(:
- 循环以获取所有类别中最长单词的长度
int len = strlen(longestWord);
- 创建格式字符串容器
char formatStr[80];
- 填充
formatStr
:sprintf(formatStr, "%s%d%s", "%", len+5, "s");
+5
是任意的,请
根据需要更改列之间的间距。 - 在每个单词的
printf()
语句中使用formatStr
。
因此,例如,示例中显示的最长单词是strawberry
。 我的建议是以编程方式将所有单词解析为缓冲区,并在它们上循环,对每个单词执行strlen()
以确定最长。 一旦你找到,在这种情况下,strawberry
,len
将是 10,所以格式说明符将是"%15s"
的(如果你使用我推荐的+5
(。 但是到那时,15
的值将位于int
变量中(例如int longest
. 由于将其直接插入到普通格式字符串:("%longests"
( 中将无法编译,因此需要将其打包成格式字符串,formatStr
如上面的项目符号所示,如下所示:
sprintf(formatStr, "%s%d%s", "%", longest + 5, "s|");
( 将看起来像:"%s15s|"
(
完成此操作后,您可以在 printf 语句中使用格式字符串
然后:
fprintf(f_2,"%-*s|",size_of_column[counter], clipboard);
成为:
fprintf(f_2,formatStr, clipboard);
(这两种方法都有效。