gpt4 book ai didi

c - fscanf 在应该返回 1 的时候始终返回 0

转载 作者:行者123 更新时间:2023-11-30 15:06:40 26 4
gpt4 key购买 nike

我有一个函数,它接受文件流并将存储在该文件中的整数读取到一维矩阵中。我遇到的问题是我的 fscanf 始终返回 0,而不是我期望的 1。我知道文件开头的格式正确且符合预期,但我不明白为什么它不会读取第一行。我做错了什么?

/* FUNCTION: readToMatrix
DESCRIPTION:
This takes an input stream and reads the file (as described in the header documentation),
filling the array with the integers contained in the input file stream.
INPUTS:
file stream, int *array, matrix width
OUTPUTS:
Writes to array
RETURN:
Returns 0 on success, nonzero on an unexpected failure.
*/

int readToMatrix( FILE *input, int *array, size_t matWidth )
{
int x,y;
long num;

for ( y = 0; y < matWidth; ++y)
{
for ( x = 0; x < matWidth-1; ++x )
{
// if fscanf doesn't read 1 number or if EOF then return
if ( fscanf(input, "%ld,", &num) != 1 || feof(input) ) return -1;
array[x + y*matWidth] = num;
}
if ( fscanf(input, "%ld ", &num) != 1 || feof(input) ) return -1;
array[x + y*matWidth] = num;
}
return 0;
}

注意:这是输入文件开头的一个简短片段。

12177,12690,12499,12985,13005,12574,12882,12896,13026,14539,13704,13539,15182,14361,14539,15333,14615,15231,

最佳答案

您的循环中存在一些小问题。修复这些,就可以正常运行了:

#include<stdio.h>
int readToMatrix( FILE *input, int *array, size_t matWidth , size_t matHeight)
{
int x,y;
long num;
for ( y = 0; y < matHeight; y++)
{
for ( x = 0; x < matWidth; x++ )
{
// if fscanf doesn't read 1 number or if EOF then return
if ( fscanf(input, "%ld,", &num) != 1 || feof(input) ) return -1;
array[x + y*matWidth] = num;
}
}
return 0;
}
int main()
{
FILE *fd;
int matWidth = 5 ;
int matHeight = 5;
int array[18];
int i;
fd=fopen("matrix.txt","r");
if(fd == NULL)
{
printf("open failed!\n");
}
else
{
readToMatrix( fd, array, matWidth , matHeight);
fclose(fd);
}
for(i=0;i<18;i++)
{
printf("%d:%d\n",i,array[i]);
}
return 0;
}

这里是matrix.txt:

12177,12690,12499,12985,13005,12574,12882,12896,13026,14539,13704,13539,15182,14361,14539,15333,14615,15231 

输出:0:121771:126902:124993:129854:130055:125746:128827:128968:130269:1453910:1370411:1353912:1518213:1436114:1453915:1533316:1461517:15231

关于c - fscanf 在应该返回 1 的时候始终返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38886819/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com