gpt4 book ai didi

c - fwrite后在txt文件上显示汉字

转载 作者:行者123 更新时间:2023-12-03 08:42:25 25 4
gpt4 key购买 nike

我想将结构中的数据写入文本文件。但是最终在文本文件中显示奇怪的字符。我已经更改了许多形式的fwrite参数,但没有任何效果。请有人帮我。对不起,长代码

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

struct Student
{
char name[30];
int id;
int score;
int score2;
int score3;
};

int main()
{
printf("Please input the information below into grade.data!\n");
printf("Ends with name's value equal to 'E'\n");
struct Student stu[10];
int i = 0, maxlength = 0; //size of longest name
printf("Name No Math Chi Eng\n");
while (true){
scanf("%s", stu[i].name);
if(maxlength < strlen(stu[i].name)) maxlength = strlen(stu[i].name);
if (stu[i].name[0] == 'E') break;
scanf("%d", &stu[i].id);
scanf("%d", &stu[i].score1);
scanf("%d", &stu[i].score2);
scanf("%d", &stu[i].score3);
i++;
}

FILE* fp;
fp = fopen("test.txt", "wb");
if (fp == NULL) {
printf("Open file error!");
exit(-1);
}

fwrite(&stu, sizeof(struct Student), 1, fp);
fclose(fp);
printf("Name%-*c No%-*c Math Chi Eng\n", maxlength-4, ' ', 7, ' ');
for (int i = 0; stu[i].name[0] != 'E'; i++) {
printf("%-*s ", maxlength, stu[i].name);
printf("%-*d ", 9, stu[i].id);
printf("%-*d ", 4, stu[i].score1);
printf("%-*d ", 3, stu[i].score2);
printf("%d\n", stu[i].score3);
}
return 0;
}

That is the input and file after fwrite is executed

最佳答案

这是因为Student之外的name结构中的成员是整数。将整数值转换为ASCII,然后将其存储在文件中。

关于c - fwrite后在txt文件上显示汉字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60548080/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com