如何阅读c语言中的数字列表
我有一个文件,其中包括以下格式的产品名称、产品数量和产品价格如何阅读c语言中的数字列表,c,file,pointers,C,File,Pointers,我有一个文件,其中包括以下格式的产品名称、产品数量和产品价格 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 pr
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;
}
使此程序更简单的最佳做法是什么?如果以下程序可以帮助您,请尝试
#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;
}
尝试使用
fgets()
获取输入行,并使用sscanf()
解析输入。非常感谢
$ gcc main.c
$ ./a.out
sum: 60.000000
$