我正在尝试从未知长度的文件中读取以逗号分隔的 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);
}
最佳答案
哦!这是一个可怕的问题。
您已获得此代码以确保您的文件大小合适;一种“调试检查”。
//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'
。
关于c - 在 C 中逐行读取 X&Y 坐标并将它们存储在不同的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52888904/