2017-06-21 24 views
-2

出于某种原因,我不明白为什么我的函数没有传递数据文件的第一个数字,但它读取最后一个数字两次。它显然在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数组中,并将其正确打印在一个函数中,我没有在这里包含它。这是我对主函数的调用。

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; 
+1

请发表[MCVE] – OldProgrammer

+1

请阅读[问]特地[MCVE]部分。 – Stargateur

+1

但是你可以阅读[问],我想? – Olaf

回答

1

您在循环之前调用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; 
} 
相关问题