gpt4 book ai didi

c - 循环在完成之前会重复自身

转载 作者:行者123 更新时间:2023-11-30 16:23:44 24 4
gpt4 key购买 nike

我正在尝试用 c 编写数据文本,但进程顺序有问题。循环在完成之前会重复自身。它必须是“是或否”,但它在询问和稍后的 scanf 过程之后打印“go”。该代码有什么问题?

#include <stdio.h>

int main(){

FILE *potr;

char go = 'e',name[20],sname[20];
int age;

potr = fopen("example.txt","w");

if(potr == NULL) printf("File cannot open");

while(go != 'n'){
printf("go\n");
scanf("%s %s %d",name,sname,&age);
fprintf(potr,"%s %s %d",name,sname,age);
printf("\ny or n :");
scanf("%c",&go);
}

fclose(potr);

return 0;
}

最佳答案

首先fopen()错误处理不正确,这个

potr = fopen("example.txt","w");
if(potr == NULL)
printf("File cannot open"); /* doesn't make any sense */

应该是

potr = fopen("example.txt","w");
if(potr == NULL) {
printf("File cannot open");
return 0; /* return if open failed */
}

其次,使用

scanf(" %c",&go); /* To avoid buffering issue i.e after char you pressed ENTER i.e 2 input. space before %c will work */

而不是

scanf("%c",&go);

示例代码:

int main(void){
FILE *potr = fopen("example.txt","w");
if(potr == NULL){
printf("File cannot open");
return 0;
}
char go = 'e',name[20],sname[20];
int age;

while(go != 'n'){
printf("go\n");
scanf("%19s%19s%d",name,sname,&age);
fprintf(potr,"%s %s %d",name,sname,age);
printf("\ny or n :");
scanf(" %c",&go); /* whitespace before %c */
}
fclose(potr);
return 0;
}

此外,在这种特殊情况下,您可以使用 do..while 而不是 while 作为第一次进入循环,无论条件是真还是假,通过分配go 作为 e。例如

do{
printf("go\n");
scanf("%19s%19s%d",name,sname,&age);
fprintf(potr,"%s %s %d",name,sname,age);
printf("\ny or n :");
scanf(" %c",&go); /* whitespace before %c */
}while(go == 'y' || go == 'Y');

关于c - 循环在完成之前会重复自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53906310/

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