1

I'm trying to write a data text with c but something is wrong with process order. Loop repeats itself before complete. It have to 'yes or no' but it prints 'go' after ask and later scanf process. What is wrong in that code?

#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;
}
Mustafa Tufan
  • 53
  • 1
  • 7

1 Answers1

1

Firstly fopen() error handling is not correct, this

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

should be

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

secondly, use

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

instead of

scanf("%c",&go);

Sample code :

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;
}

Also in this particular case you can use do..while instead of while as first time you want to enter into loop irrespective of condition is true or false by assigning go as e. For e.g

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');
Achal
  • 11,821
  • 2
  • 15
  • 37