gpt4 book ai didi

无法弄清楚为什么我的函数没有传递文件的第一个数字,而是传递最后一个数字两次

转载 作者:行者123 更新时间:2023-11-30 20:20:49 25 4
gpt4 key购买 nike

出于某种原因,我无法弄清楚为什么我的函数没有传递数据文件的第一个数字,但它读取了最后一个数字两次。显然,它在 search_mpn_table 函数中很小,但我无法具体说明它,因为我对编码相对较新。提前致谢。

int search_mpn_table(bacteria_t z[], int size, char combo[])
{
int i;
int combocorrect=-1;

for(i=0;i<size;i++)
{
if(strcmp(z[i].combo,combo)==0)
{
combocorrect=i;
printf("%s\n", z[i].combo);
}
}
return combocorrect;
}

我将其加载到 z 数组中,并在此处未包含的函数中正确打印了它。这是我对 main 中函数的调用。

FILE *outfilep=fopen(foutput,"a");
FILE *inputu=fopen("user_input","r");

status=fscanf(inputu,"%s", combo);
while(status!=EOF)
{
status=fscanf(inputu,"%s", combo);
correct=search_mpn_table(z,datasize,combo);
if(correct==-1)
{
fprintf(outfilep,"\nCombination of Positives were not found for %s", combo);
}

else
{
fprintf(outfilep,"\n%s MPN=%d, 95 pct of examples contain between %d and %d Bacteria per 100mL.", z[correct].combo, z[correct].mpn, z[correct].upper, z[correct].lower);
}
}
fclose(inputu);
fclose(outfilep);
return 0;

最佳答案

您在循环之前调用 fscanf,然后在循环内的第一时刻再次调用。因此,您的程序会忽略(覆盖)第一行输入。您还处理输入的最后一行两次,因为在 fscanf (很可能)在循环内的 EOF 上失败后,您仍然处理组合,其中仍然包含您已经处理过的输入的最后一行。

将 fscanfs 移动到 while 语句中,如下所示:

#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>

#define STR(x) #x
#define SSTR(x) STR(x)

#define MAX_STR 1024

void process(FILE *out, const char *str)
{
fprintf(out, "%s\n", str);
}

int main()
{
FILE *outfilep = fopen("user_output", "a");
FILE *inputu = fopen("user_input", "r");
char combo[MAX_STR + 1];
int status;

if (outfilep == NULL || inputu == NULL)
abort();

while ((status = fscanf(inputu, "%" SSTR(MAX_STR) "s", combo)) == 1)
{
process(outfilep, combo);

/* do other stuff */
}

fclose(inputu);
fclose(outfilep);

return 0;
}

关于无法弄清楚为什么我的函数没有传递文件的第一个数字,而是传递最后一个数字两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44665327/

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