我目前正在开发一个程序,该程序获取 5 种产品的数量和价格并将其写入文本文件,以表格的形式打印整个数据,然后打印所选价格之一。但是,它仅将最后一个产品的数据写入打印表,并且所选产品的价格打印 0。
#include <stdio.h>
#include <stdlib.h>
typedef struct Stock {
int quantity;
float price;
};
void print_stock(Stock a, int len) {
for (int code = 0; code < len; code++)
printf("code[%d] %4f %4d\n", code, a.price, a.quantity);
}
int main() {
FILE *fp = fopen("stocks.txt", "w+");
Stock a;
if (fp == NULL) {
puts("File couldn't be opened.\n");
exit(1);
}
int code, c;
char arr_code[5];
int len = sizeof(arr_code) / sizeof(arr_code[0]);
int option;
printf("There will be %d product(s) in the stock.\n", len);
for (code = 0; code < len; code++) {
printf("Enter the product's quantity:");
scanf("%d", &a.quantity);
printf("Enter the product's price:");
scanf("%f", &a.price);
fprintf(fp, "quantity-%7d price-%7f\n", a.quantity, a.price);
}
print_stock(a, len);
fclose(fp);
FILE *fp2 = fopen("stocks.txt", "r");
printf("Enter an option(starts from 0):\n");
scanf("%d", &option);
fseek(fp2, option * sizeof(struct Stock), SEEK_SET);
fread(&a, sizeof(struct Stock), 1, fp2);
printf("the price is %f\n", a.price);
fclose(fp2);
}
我期望输出是这样的:
There will be 5 product(s) in the stock.
Enter the product's quantity:76
Enter the product's price:88
Enter the product's quantity:5
Enter the product's price:44
Enter the product's quantity:89
Enter the product's price:32
Enter the product's quantity:54
Enter the product's price:33
Enter the product's quantity:94
Enter the product's price:65
code[0] 88.000000 76
code[1] 44.000000 5
code[2] 32.000000 89
code[3] 33.000000 54
code[4] 65.000000 94
Enter an option(starts from 0):
2
the price is 32.000000
但我得到这个结果:
There will be 5 product(s) in the stock.
Enter the product's quantity:76
Enter the product's price:88
Enter the product's quantity:5
Enter the product's price:44
Enter the product's quantity:89
Enter the product's price:32
Enter the product's quantity:54
Enter the product's price:33
Enter the product's quantity:94
Enter the product's price:65
code[0] 65.000000 94
code[1] 65.000000 94
code[2] 65.000000 94
code[3] 65.000000 94
code[4] 65.000000 94
Enter an option(starts from 0):
3
the price is 0.000000
最佳答案
到目前为止,您正在多次打印 a
的最新内容。
只需将 len
传递为 1,将 print_stock
函数调用移动到 for
循环内即可。
for (code = 0; code < len; code++) {
printf("Enter the product's quantity:");
scanf("%d", &a.quantity);
printf("Enter the product's price:");
scanf("%f", &a.price);
fprintf(fp, "quantity-%7d price-%7f\n", a.quantity, a.price);
print_stock(a, 1);
}
此外,打印时还应该考虑索引。
void print_stock(Stock a[], int len) {
for (int code = 0; code < len; code++)
printf("code[%d] %4f %4d\n", code, a[code].price, a[code].quantity);
}
关于c - 在 C 中使用文件中的库存数据时,数据打印不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55862522/