【发布时间】:2022-01-21 14:36:27
【问题描述】:
我的 .txt 文件有问题,因为我必须创建客户记录,然后才能更改数据。会发生以下情况,当我创建客户端时,数据如下所示:
但是当我去编辑名称或国家时,就是这样,而我想要你在不创建新行的情况下进行更改。
- 姓名:
- 国家:
我可能遗漏了什么或者这是保存文件的方法,但我不知道!!
这是我的代码:
typedef struct {
char name[80];
char country[10];
int tin;
int customer_code;
} CLIENT, upd, add;
void
edit_customer()
{
CLIENT add, upd;
int choice;
FILE *bd;
bd = fopen("bd.txt", "a");
printf("Enter the customer code: ");
scanf("%d", &add.customer_code);
printf("\nSelect the type of change you want:\n1 - Name\n2 - Country\n\nEnter your choice:");
scanf("%d", &choice);
switch (choice) {
case 1:
fgets(upd.name, 80, stdin);
printf("Type your name: ");
scanf("%[^\n]s", upd.name);
fprintf(bd, "code: %d | name: %s | tin: %d | country: %s \n",
add.customer_code, upd.name, add.tin, add.country);
printf("Changes saved!");
break;
case 2:
printf("Enter the Country:");
scanf("%s", upd.country);
fprintf(bd, "code: %d | name: %s | tin: %i | country: %s \n",
add.customer_code, add.name, add.tin, upd.country);
printf("Changes saved!");
break;
}
}
【问题讨论】:
-
请不要发布链接到图片的文本。请编辑您的问题,然后从调试/控制台窗口复制并粘贴到此处的代码块中。
-
你有 UB(未定义的行为)。 struct
upd是 undefined。当您在 eithercase中执行scanf时,other 字段未定义。 (例如)对于case 1:,它定义了upd.name,但其他字段upd.country是随机的。另外,请注意您为upd执行scanf,但为add执行printf,这是另一个错误。 -
回复:
%[^\n]s;%[]和%s是不同的格式说明符。您不需要将它们组合起来。
标签: c