循环在完成之前重复自身

时间:2018-12-23 18:53:03

标签: c loops

我正在尝试使用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;
}

1 个答案:

答案 0 :(得分: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设置为{{1},而无论条件是真还是假,都可以使用while而不是go作为第一次进入循环}}。对于例如

e