C语言 从 sscanf 读取的数字为 0



社区美好的一天。我尝试编写的代码必须从文件中读取整数,同时跳过以 # 开头的行。我的问题是没有读取任何数字,而是返回 0。 该文件如下所示:

#hello
#myname
#is
#file
122 4838
112   393949
1239 233
29393 44949
3 2
445 566

输出为:

0       0
Read 0 numbers
0       0
Read 0 numbers
0       0
Read 0 numbers
0       0
Read 0 numbers 

代码为:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct {
int start;
int end;
} path;
int main()
{
int test; 
path* array=malloc(sizeof(path));
if(array==NULL) {
printf("Error allocating memoryn");
abort();
}

FILE* fd=fopen("Test.txt","r");
if(fd==NULL) {
printf("Error opening filen");
abort();
}
char buff[200];
int counter=0;
char c;
while(fgets(buff,200,fd)&&counter<6) {
c=buff[0];
if(c=="#") {
continue;
}
test=sscanf(&buff,"%d%d",array[counter].start,array[counter].end);
printf("%dt%dn",array[counter].start,array[counter].end);
printf("Read %d numbersn", test);
counter++;
}
fclose(fd);
free(array);
return 0;
}

代码中的问题在于对sscanf函数的参数。这需要作为相应格式字段的"目标"的所有变量的地址(但读取char[]字符串是不同的,因为数组名称在用作函数参数时会衰减为指针(。

因此,在您的情况下,要读取两个整数结构成员,您应该使用以下命令:

test = sscanf(buff, "%d%d", &array[counter].start, &array[counter].end);

注意 1:另外,您不需要buff参数上的&运算符,因为这会衰减,如上所述!

注 2:由于.(结构成员访问运算符(的优先级高于&(地址运算符(,因此表达式&array[counter].start&(array[counter].start)相同 - 但您可能更喜欢后者,更明确的代码,因为这可以使其他人更清楚地阅读和理解。

请随时要求进一步澄清和/或解释。

最新更新