首页 > 解决方案 > 从文本中获取特定字符并在 C 中打印相关行

问题描述

我在 C 中的 I/O 文件处理有几个问题。我有一个这样的文本文件:

AAA    1    80
BBB    1    60
CCC    2    20
DDD    1    70
EEE    2    15
FFF    2    30
GGG    2    75
HHH    1    25
JJJ    2    35

我的目标是如果用户输入 1 我需要打印:

AAA    1    80
BBB    1    60
DDD    1    70
HHH    1    25

并总结它们的值(80+60+70+25),如果用户输入 2,则应用相同的东西。

我编写了这样的代码:

FILE *fPtr;
    char str[MAXCHAR];
    char* fileName = "/home/levent/Masaüstü/data.txt";
    int productType;

    fPtr = fopen(fileName, "r");

    if(fPtr == NULL){
        printf("Error! Colud not find file %s", fileName);
        return 1;
    }

    printf("Enter product type code (1 or 2): ");
    scanf("%d", &productType);

    while (fgets(str, MAXCHAR, fPtr) != NULL){
        printf("%s", str);        
    }

正如您假设此代码打印整个文本文件一样。如何管理我的目标?

标签: cfileio

解决方案


您可以使用fscanf和解析每一行的每个组件,然后在同一个循环中,您可以对有效值求和:

以下是一些评论的可能实施:

现场演示

//...
#define MAXCHAR 100
//...
int fileProductType; //product type read from file
int value;           //value read from file
int sum = 0;         //to store the sum of the values

//...

//scan all file lines
while (fscanf(fPtr, "%99s %d %d", str, &fileProductType, &value) == 3){
    if (productType == fileProductType){ //if the type is correct
        printf("%s %d %d\n", str, fileProductType, value); //print line 
        sum += value; //sum values
    }    
}

if(sum)                       //if the product type is found
    printf("Sum: %d\n", sum); //print sum
else
    puts("No mach found!");
//...

另一种选择是用于sscanf解析fgets. 其余的将或多或少相同。


推荐阅读