【问题标题】:Reading in X&Y co-ordinates, line by line, in C and storing them in different arrays在 C 中逐行读取 XY 坐标并将它们存储在不同的数组中
【发布时间】: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);
}

【问题讨论】:

标签: c arrays csv parsing scanf


【解决方案1】:

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

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

//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'

【讨论】:

  • 完美,如此简单的解决方案,大小元素就在那里,因为我不知道文件中可能有多少行坐标,如果这有意义的话。谢谢!
  • @Dave 哦;我以为那是为了调试!那么,这是一个没有我想象的那么可怕的问题。将来,在 Stack Overflow 上发帖之前尝试创建一个minimal reproducible example;您可能已经通过这种方式发现了问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-09
  • 2020-08-26
  • 2021-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-27
相关资源
最近更新 更多