gpt4 book ai didi

c - fwrite(),将我的输入和一些垃圾写入我的文件

转载 作者:太空宇宙 更新时间:2023-11-03 23:39:55 25 4
gpt4 key购买 nike

我的代码:

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

typedef struct{
char name[50];
char phone[11];
}contato;

int main(){
contato c;
int i = 0;
FILE *fp = fopen("lista_contato.txt", "w");

printf("Nome: ");
fflush(stdin);
fgets(c.name, 50, stdin);
printf("Telefone: ");
fflush(stdin);
fgets(c.phone, 11, stdin);

fwrite(&c, 1, sizeof(contato), fp);

fclose(fp);

return 0;
}

我输入的名字:“名字姓氏”

我的电话输入:“1234”

我在文件上的输出:“名字姓氏 ¿@ °@ Vw ( x ¸þa 电话 "

这段代码发生了什么,我该如何解决?

最佳答案

你需要初始化c。在您当前的代码中,它将只包含随机数据。在将任何数据插入 c: 之前添加此行:

memset(&c, 0, sizeof(contato));

关于c - fwrite(),将我的输入和一些垃圾写入我的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48622145/

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