Reputation: 11
As a Chinese university student studying computer-related majors, I am working on a major assignment assigned by my teacher to create a restaurant management system. However, when I finished my code, I found that CLion cannot correctly read the dish names stored in the TXT file. enter image description here enter image description here
I tried using '%s' to input the string and '%49[^,]' to make it understand the content before the ',' but neither worked. Additionally, I also tried changing the input method by using '\n' to make it read the content before the newline character, but it still couldn't effectively write the dish names.
void loadMenuFromFile(const char *filename) {
setlocale(LC_ALL, "zh_CN.GBK");
FILE *file = fopen(filename, "r");
if (file == NULL) {
perror("无法打开文件");
return;
}
// 初始化 itemCount 为 0
char line[100]; // 用于存储读取的整行数据
// 读取文件,直到文件末尾
while (fgets(line, sizeof(line), file)) {
printf("读取行: %s\n", line); // 打印读取的行
int result = sscanf(line, "菜品ID: %d\n 名称: %49[^\n]\n 价格: %f\n 成本: %f\n",
&menu.items[count].id,
menu.items[count].name,
&menu.items[count].price,
&menu.items[count].cost);
if (result == 4) {
printf("成功解析: ID=%d, 名称=%s, 价格=%.2f, 成本=%.2f",
menu.items[count].id,
menu.items[count].name,
menu.items[count].price,
menu.items[count].cost);
count++; // 成功解析后增加 itemCount
} else {
printf("解析失败,读取行内容: %s\n", line);
}
}
fclose(file);
printf("菜单数据已从文件 %s 加载,读取了 %d 个菜品\n", filename, count);
}
void loadMenuFromFile(const char *filename) {
setlocale(LC_ALL, "zh_CN.GBK");
FILE *file = fopen(filename, "r");
if (file == NULL) {
perror("无法打开文件");
return;
}
// 初始化 itemCount 为 0
char line[100]; // 用于存储读取的整行数据
// 读取文件,直到文件末尾
while (fgets(line, sizeof(line), file)) {
printf("读取行: %s\n", line); // 打印读取的行
int result = sscanf(line, "菜品ID: %d, 名称: %49[^,], 价格: %f ,成本: %f",
&menu.items[count].id,
menu.items[count].name,
&menu.items[count].price,
&menu.items[count].cost);
if (result == 4) {
printf("成功解析: ID=%d, 名称=%s, 价格=%.2f, 成本=%.2f",
menu.items[count].id,
menu.items[count].name,
menu.items[count].price,
menu.items[count].cost);
count++; // 成功解析后增加 itemCount
} else {
printf("解析失败,读取行内容: %s\n", line);
}
}
fclose(file);
printf("菜单数据已从文件 %s 加载,读取了 %d 个菜品\n", filename, count);
}
void saveMenuToFile(const char *filename){
FILE *file = fopen(filename, "w");
if (file == NULL) {
perror("无法打开文件");
return;
}
// 将菜单项写入文件
for (int i = 0; i < count; i++) {
fprintf(file, "菜品ID: %d 名称: %s 价格: %.2f 成本: %.2f",
menu.items[i].id, menu.items[i].name, menu.items[i].price, menu.items[i].cost);
}
fclose(file);
printf("菜单数据已保存到文件 %s\n", filename);
}
I tried everything except Json part.......I don't know why it can't scanf words from txt to menu correctly. the txt words coding is GBK and clion's product is GBK too.
Upvotes: 1
Views: 52