在C中逐行读取X&Y坐标并将它们存储在不同的数组中

时间:2018-10-19 08:50:39

标签: c arrays csv parsing scanf

我正在尝试从长度未知的文件中读取由逗号分隔的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);
}

1 个答案:

答案 0 :(得分:2)

哦!这是一个可怕的问题。

您已获得此代码,以确保文件大小正确;一种“调试检查”。

//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);

但这实际上是导致此错误的原因,因为它“用完了”整个文件,这意味着永远不会从文件中加载值,而您只需要事先获取存储在该内存中的任何内容即可。

要解决此问题,请删除您的检查代码或在其末尾添加该行(在printf之前或之后):

rewind(myFile);

这将查找文件的开头,因此您可以从文件中读取实际数据。您可以还可以使用:

fseek(myFile, 0, SEEK_SET);

做同样的事情。


在处理此问题时,我将修复您的scanf行:

        fscanf(myFile, "%d,%d\n", &xArray[i], &yArray[i]);

在格式字符串的末尾需要一个字符,因为两行之间有一个'\n'