手工创建一个文本文件,里面包含两条商品的信息,内容如下:
210001 电动平衡车 Phoenix 859
210002 三层保暖卫衣 雅鹿 149.9
根据商品信息,设计结构体类型,在主程序中创建两个结构体变量,从文件把商品信息读入两个变量。设计一个函数可以用如下格式输出一件商品的信息:
商品编号:210001
商品名称:电动平衡车
生产厂商:Phoenix
价格:859.00
在主函数中输出两个结构体变量中商品的信息。
#include <stdio.h>
#include <malloc.h>
#include <string.h>
struct goods
{
int id;
char name[100];
char brand[100];
float price;
};
void printGood(struct goods *t);
int main()
{
struct goods t1, t2;
errno_t err;
FILE *File;
err = fopen_s(&File, "test.txt", "r");
if (err != 0)
{
printf("文件打开失败\n");
return 0;
}
else
{
fscanf(File, "%d%s%s%f", &t1.id, t1.name, t1.brand, &t1.price);
fscanf(File, "%d%s%s%f", &t2.id, t2.name, t2.brand, &t2.price);
}
printGood(&t1);
printGood(&t2);
return 0;
}
void printGood(struct goods *t)
{
printf("商品编号:%d\n商品名称:%s\n生产厂商:%s\n价格:%.2f\n", t->id, t->name, t->brand, t->price);
}