C 将档案的行转换为数组 [英] C Turning lines of an archive into arrays
问题描述
我有一个存档,我想把每一行都变成一个数组:v[i].data.但是,当我运行代码时,它显示数组为零.有什么我应该改变的吗?
I have an archive and I want to turn every line into an array: v[i].data. However, when I run the code it shows zeros for the arrays. Is there anything I should change?
输入
1760
02/20/18,11403.7
02/19/18,11225.3
02/18/18,10551.8
02/17/18,11112.7
02/16/18,10233.9
1760
02/20/18,11403.7
02/19/18,11225.3
02/18/18,10551.8
02/17/18,11112.7
02/16/18,10233.9
实际输出
1761
0
预期产出
1761
02/20/18,11403.7
1761
02/20/18,11403.7
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
typedef struct{
char data[20];
}vetor;
int main(int argc,char *argv[]){
FILE *csv;
if((csv=fopen(argv[1], "r")) == NULL )
{
printf("not found csv\n");
exit(1);
}
long int a=0;
char linha[256];
char *token = NULL;
if(fgets(linha, sizeof(linha), csv)) //counting lines
{
token = strtok(linha, "\n");
a =(1 + atoi(token));
}
printf("%d\n", a);
rewind(csv);
vetor *v;
v=(vetor*)malloc(a*sizeof(vetor));
char linha2[256];
while (fgets(linha2, sizeof(linha2), csv) != 0)
{
fseek(csv, +1, SEEK_CUR);
for(int i=0;i<a;i++)
{
fscanf(csv, "%[^\n]", v[i].data);
}
}
printf("%s\n", v[0].data);
fclose(csv);
return 0;
}
推荐答案
有很多错误,所以我继续重写了问题区域,并用评论解释了我所做的
There were a number of mistakes so I went ahead and rewrote the problem areas with comments explaining what I did
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
char data[20];
}vetor;
int main(int argc,char *argv[]){
FILE *csv;
if((csv=fopen(argv[1], "r")) == NULL )
{
printf("not found csv\n");
exit(1);
}
char line[20];
// Read number of lines
int num_lines = 0;
if (!fgets(line, sizeof(line), csv)) {
printf("Cannot read line\n");
exit(1);
}
char* token = strtok(line, "\n");
num_lines = atoi(token) + 1;
vetor* v = malloc(num_lines * sizeof(vetor));
// Fill in vetor
int i = 0;
while (fgets(line, sizeof(line), csv) != NULL) {
int len = strlen(line);
line[len-1] = '\0'; // replace newline with string terminator
strcpy(v[i].data, line); //copy line into v[i].data
i++;
}
printf("%d\n", num_lines);
for (i = 0; i < num_lines; i++) {
printf("%s\n", v[i].data);
}
return 0;
}
我认为主要的错误是对如何最好地阅读每一行信息的误解.如果我理解正确,您希望每个 02/20/18,11403.7
行都是 vetor
数组中的一个元素.
I think the main mistake was a misunderstanding of how best to read in each line of information. If I understood correctly you want each 02/20/18,11403.7
line to be an element in the vetor
array.
最简单的方法是使用 fgets 一次获取每一行
The easiest way is to simply get each line one at a time with fgets
while (fgets(line, sizeof(line), csv) != NULL)
将结束符由换行符改为字符串终止符'\0'
Change the ending character from newline to the string terminating character '\0'
int len = strlen(line);
line[len-1] = '\0';
然后将字符串复制到vetor
的第i个元素中,并更新i
用于下一次循环迭代.
Then copy the string into the ith element of vetor
and update i
for the next iteration of the loop.
strcpy(v[i].data, line);
i++;
这篇关于C 将档案的行转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!