简体   繁体   English

从文本文件中读取并总结第一个单词相同的行

[英]Reading from text file and summing lines where first words are the same

I have a text file with such information:我有一个包含此类信息的文本文件:

CD-R 50
DVD-R 20
CD-R 15
BINDERS 30
RADIO 35
CD-R 100

I have to read that text file and sum the same products.我必须阅读该文本文件并对相同的产品求和。 Output Should be like that Output 应该是这样的

CD-R 165
DVD-R 20
BINDERS 30
RADIO 35

Here is my code:这是我的代码:

#include <stdlib.h>
#include <stdio.h>
int main(){
FILE *f = fopen("file.txt","r")
char str[100];
int arr[100];
int entity;
int products = 6,i;
for(i=0;i<products;i++){
fscanf(f,"%s %d",na[i],&entity);
arr[i]=entity;
}
    int count=1;
    for(i=0;i<prod;i++){
        for(j=i+1;j<prod;j++){
            if(strcmp(na[i],na[j])==0){
                arr[i]+=arr[j];
            }
        }
    }
}

so I read every line without any problem and put each name and entity in character and integer array, then I count distinct product names.所以我毫无问题地阅读了每一行,并将每个名称和实体放在字符和 integer 数组中,然后我计算不同的产品名称。 Then i want to to print output as shown above but I find it difficult could use little hint.然后我想打印 output ,如上所示,但我发现很难使用很少的提示。

As you asked for hints, I will not provide a full solution.正如您要求的提示,我不会提供完整的解决方案。

  1. You are dealing with a combination of name and values.您正在处理名称和值的组合。 Therefore you should drop your separate arrays and use a struct that combines name and number.因此,您应该删除单独的 arrays 并使用结合名称和编号的结构。 Then create an array for that struct.然后为该结构创建一个数组。
#define MAX_NAME     100
#define MAX_PRODUCTS  10
typedef struct product
{
  char product_name[MAX_NAME]
  int  number;
} product;

product products[MAX_PRODUCTS];
  1. You are dealing with an unsorted file that contains multiple lines with same product name which you want to combine to one entry.您正在处理一个未排序的文件,该文件包含多个具有相同产品名称的行,您希望将这些行合并到一个条目中。
    Instead of reading directly into your array, read each line into a temp buffer first.不要直接读入你的数组,而是先将每一行读入一个临时缓冲区。 Then check if you already have the same product in your array.然后检查您的阵列中是否已经有相同的产品。 Depending on that, either add new product to your array or add the new number to the old entry in the array.根据这一点,要么将新产品添加到您的阵列中,要么将新编号添加到阵列中的旧条目中。

  2. Afterwards print all entries in your array.然后打印数组中的所有条目。

  3. It is not clear if you can know in advance how many different entries you can have in your file.目前尚不清楚您是否可以提前知道您的文件中有多少不同的条目。 If you cannot know it, you might switch from that array to a dynamically allocated buffer that is (re)allocated with proper size.如果您不知道,您可能会从该数组切换到动态分配的缓冲区,该缓冲区以适当的大小(重新)分配。

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

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