【问题标题】:How to read the list of number in c [closed]如何阅读c中的数字列表[关闭]
【发布时间】:2017-08-16 16:22:26
【问题描述】:

我有一个文件,其中包含以下格式的产品名称、产品数量和产品价格。

file.txt

3
Product   Qty  Price
Tv        2    10
Mobile    3    20
Computer  5    30

我想从产品列表上方给出的整数(例如3)中读取产品的数量,并计算产品的总价格。程序将使用struct读取产品详细信息,例如

struct product {         
    Char name[30];
    int qty ;
    float price;        
} 

使这个程序更容易的最佳做法是什么?

【问题讨论】:

  • 尝试使用fgets()获取输入行,使用sscanf()解析输入。

标签: c file pointers


【解决方案1】:

如果以下程序可以帮助您,请尝试。

#include <stdio.h>
#include <stdlib.h>

struct product {
    char name[30];
    int qty;
    float price;
};

int main(void) {
    int count = 0;
    char line[100];
    FILE *fptr;
    fptr = fopen("file.txt", "r");
    fscanf(fptr, "%d", &count); // count = 3
    struct product *p = malloc(sizeof(struct product));
    int i = 0;
    double sum = 0;
    while (i < count + 2 && fgets(line, sizeof(line), fptr) != NULL) {
        if (i > 1) {
            sscanf(line, "%s %d %f\n", (*p).name, &(*p).qty, &(*p).price);
            sum = sum + (*p).price;
        }
        i++;
    }
    printf("sum: %f\n", sum);
    free(p);
    return 0;
}

测试

$ gcc main.c                                                                   
$ ./a.out                                                                      
sum: 60.000000
$ 

【讨论】:

  • 非常感谢
猜你喜欢
  • 1970-01-01
  • 2021-08-10
  • 1970-01-01
  • 2010-11-23
  • 1970-01-01
  • 2016-09-15
  • 2018-11-15
  • 2011-06-04
  • 2014-04-04
相关资源
最近更新 更多