从sscanf读取的数字为0
大家好。我试图编写的代码必须从文件中读取整数,同时跳过以#开头的行。我的问题是没有读取任何数字,而是返回0。 该文件如下所示:从sscanf读取的数字为0,c,file-io,zero,C,File Io,Zero,大家好。我试图编写的代码必须从文件中读取整数,同时跳过以#开头的行。我的问题是没有读取任何数字,而是返回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
#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;
}
#包括
#包括
#包括
类型定义结构{
int启动;
内端;
}路径;
int main()
{
智力测验;
path*array=malloc(sizeof(path));
if(数组==NULL){
printf(“分配内存时出错”);
中止();
}
文件*fd=fopen(“Test.txt”、“r”);
如果(fd==NULL){
printf(“打开文件时出错”);
中止();
}
字符buff[200];
int计数器=0;
字符c;
while(fgets(buff,200,fd)&&counter代码中的问题在于sscanf
函数的参数。这需要所有变量的地址,这些变量是相应格式字段的“目标”(但在char[]中读取)
strings是不同的,因为数组名用作函数参数时会有所不同)
因此,在您的情况下,要读入两个整数结构成员,您应该使用:
test=sscanf(buff,“%d%d”,&array[counter]。开始,&array[counter]。结束);
注1:另外,在buff
参数上不需要&
运算符,因为这将衰减,如上所述
注2:由于
(结构成员访问运算符)的值大于&
(运算符地址),因此表达式&数组[counter].start
与&(数组[counter].start)相同
-但您可能更喜欢后者,更明确的代码,因为这可以让其他人更清楚地阅读和理解
请随时要求进一步澄清和/或解释。:-)从时间上看,我猜当我发表评论时,你已经在编辑过程中了。做得好。而且只输入了一个字。令人印象深刻。非常感谢你指出。我会选择这个答案,但我遇到了另一个问题。我会提出另一个问题,但问题有点类似,所以我决定编辑这个。@Azzarian这是一个s简单输入错误:在if(c==“#”)中…
您正在将单个字符,c
与字符串进行比较!改用这个,所有内容都应该是不正确的boo:if(c==”#“)…
(单引号,而不是双引号)。(很抱歉,我在发布答案时错过了它!)@阿德里安·莫尔:你是一个和蔼可亲的人,非常感谢你的帮助。你不应该通过编辑一个已经存在的问题来提出新问题,即使它看起来与你相似。任何使现有答案看起来错误的更改都应该避免。我不确定我是否正确阅读了你的评论。看起来你们两个是幸运的。在这个规范中在这种情况下,您可以保持原样,但为了将来,请理解,在有答案时进行编辑被视为“移动目标问题”,一点也不受欢迎。请提供给@AdrianMole以回滚您最近对该问题所做的编辑。