简体   繁体   English

将从文本文件读取的值相加 - C 编程

[英]Adding up values read from text file - C programming

I'm still new to C. I need to find the total transaction for combo and ala-carte.我还是 C 的新手。我需要找到组合和点菜的总交易。 Hence, I created a function to read through each line and then add up to get the total combo meal and total ala-carte transactions inside my while loop.因此,我创建了一个函数来读取每一行,然后相加得到我的 while 循环中的总组合餐和总单点交易。 However, I'm not getting any values printed out at all.但是,我根本没有打印出任何值。

output from daily_transactions function: Daily_transactions 函数的输出:

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

I coded it using fscanf()我使用 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);          

text file:文本文件:

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

edit: the function to print out the transactions编辑:打印交易的功能

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("------------------------------------");
}

There are multiple ways of solving this problem, but here is my code.有多种方法可以解决这个问题,但这是我的代码。 I am not sure if it works, because I have not tested it yet.我不确定它是否有效,因为我还没有测试过。 But hopefully it gives you an idea on how to solve the problem.但希望它能让您了解如何解决问题。

#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); 

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM