【发布时间】:2016-12-17 15:06:25
【问题描述】:
我有一个函数,它接收文件流并将存储在该文件中的整数读入一维矩阵。我遇到的问题是我的 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;
}
注意:这是输入文件开头的简短 sn-p。
12177,12690,12499,12985,13005,12574,12882,12896,13026,14539,13704,13539,15182,14361,14539,15333,14615,15231,
【问题讨论】:
-
你在哪里打开你的文件?
-
文件是在调用它的函数中打开的。
-
哪个 fscanf 调用?
-
fscanf is consistently returning 0, not 1 like I expect永远记住,当问题是“标准库中是否存在错误,或者我做错了什么?”答案几乎总是“你做错了什么”。 -
@John3136 当然我做错了什么!只需要弄清楚它是什么。