gpt4 book ai didi

c - 从 sscanf 读取的数字为 0

转载 作者:行者123 更新时间:2023-12-04 10:46:38 25 4
gpt4 key购买 nike

社区的美好一天。我正在尝试编写的代码必须在跳过以 # 开头的行的同时从文件中读取整数。我的问题是没有读取任何数字,而是返回 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 memory\n");
abort();
}


FILE* fd=fopen("Test.txt","r");
if(fd==NULL) {
printf("Error opening file\n");
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("%d\t%d\n",array[counter].start,array[counter].end);
printf("Read %d numbers\n", test);
counter++;
}

fclose(fd);
free(array);
return 0;
}

最佳答案

您代码中的问题在于您对 sscanf 的参数。功能。这需要 地址 作为相应格式字段的“目标”的所有变量(但读取 char[] 字符串是不同的,因为数组名称在用作函数参数时为 decay to a pointer)。

所以,在你的情况下,要读入两个整数结构成员,你应该使用这个:

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

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

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

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

关于c - 从 sscanf 读取的数字为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59677166/

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