【发布时间】:2019-03-24 03:23:38
【问题描述】:
我正在尝试从长度未知的文件中读取逗号分隔的 X 和 Y 整数列表,并将它们存储到两个数组中。当我来打印我的数组时,我得到的值根本不正确。我正在读的文件格式是这样的;
60,229
15,221
62,59
96,120
16,97
41,290
52,206
78,220
29,176
25,138
57,252
63,204
94,130
这是我目前得到的代码:
#include <stdio.h>
#include <stdlib.h>
int main()
{
//creating a file pointer
FILE *myFile;
//telling the pointer to open the file and what it is called
myFile = fopen("data.txt", "r");
//variables
int size = 0;
int ch = 0;
while(!feof(myFile))
{
ch = fgetc(myFile);
if(ch == '\n') {
size++;
}
}
//check that the right number of lines is shown
printf("size is %d",size);
//create arrays
int xArray[size+1];
int yArray[size+1];
int i,n;
//read each line of two numbers seperated by , into the array
for (i = 0; i <size; i++) {
fscanf(myFile, "%d,%d", &xArray[i], &yArray[i]);
}
//print each set of co-oridantes
for (n = 0; n <size; n++){
printf("x = %d Y = %d\n", xArray[n],yArray[n] );
}
fclose(myFile);
}
【问题讨论】:
-
您需要将文件指针重置为文件的开头。在第一个
for循环之前执行rewind(myFile)。
标签: c arrays csv parsing scanf