添加从文本文件中读取的值 - C编程

时间:2017-10-27 19:45:32

标签: c

我还是C的新手。我需要找到combo和ala-carte的总交易。因此,我创建了一个函数来读取每一行,然后加起来得到总的组合餐和我的while循环中的总ala-carte事务。但是,我根本没有打印任何值。

来自daily_transactions函数的输出:

   Total combo meal transaction : 0
   Total ala-carte transaction : 0
   Total sales : RM 0.00

我使用fscanf()

对其进行编码
    tfptr = fopen("trans.txt", "r");
    //loops until end of file to read last line
    while( fgets(str, sizeof(str), tfptr)!=NULL ){ //fgets() will return NULL when the file is over                                                                                                     
        fscanf(tfptr, "%u:%u:%f\n", &combo_trans, &ala_trans, &total);
        c_trans += combo_trans;
        a_trans += ala_trans;
        grand_total += total;
    }                                           
    daily_transactions(c_trans, a_trans, grand_total);                                                                                  
    fclose(tfptr);          

文本文件:

0:1:7.98
1:1:20.97
2:1:35.96
2:2:44.95
2:2:44.95
3:2:55.94

编辑:打印交易的功能

void daily_transactions(int combo_trans, int ala_trans, float grand_total){
    printf("--------------------------------\n");
    printf("   Daily Transactions\n");
    printf("--------------------------------\n");
    printf("Total combo meal transaction : %d\n", combo_trans);
    printf("Total ala-carte transaction : %d\n", ala_trans);
    printf("Total sales : RM %.2f\n", grand_total);                     
    puts("------------------------------------");
}

1 个答案:

答案 0 :(得分:0)

有多种方法可以解决这个问题,但这是我的代码。我不确定它是否有效,因为我还没有测试过它。但希望它可以让您了解如何解决问题。

#include<stdio.h>

int main(void)

{ 
  FILE *infile;

  infile=fopen("filein","r");

  int num_trans=0;
  int j=0;
  int combomeal[20],alameal[20];
  totalsales[20]={0};
  totalcombo[20]={0};
  totalala[20]={0};


 while(fscanf(infile,"%d %d",&combomeal[num_trans],&alameal[num_trans]) !=EOF) num_trans++;


 printf(" Total Combo Meal    Total Ala Meal      Total Sales\n");

  for(j=0;j<num_trans;j++)
   {
     totalcombo[j]+=combomeal[j];
     totalala[j]+=totalala[j];
     totalsales[j]=combomeal[j]+totalala[j];
     printf("  %d                    %d                     %d\n",totalcombo[j],totalala[j],totalsales[j]);      
   }


 fclose(infile); 

}