首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >fwrite后在txt文件上显示中文字符

fwrite后在txt文件上显示中文字符
EN

Stack Overflow用户
提问于 2020-03-05 22:52:52
回答 1查看 300关注 0票数 0

我想把结构化数据写到一个文本文件中。但它最终会在文本文件中显示奇怪的字符。我已经改变了许多形式的fwrite参数,但都不起作用。请谁来帮帮我。抱歉,代码太长了

代码语言:javascript
复制
#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;
}

EN

回答 1

Stack Overflow用户

发布于 2020-03-06 16:10:43

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60548080

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档