0

I have a code that is suppose to ask a user for a car manufacturer and then store it inside a txt file (this is part of introductory course in C). I have the following menu for calling the function inside int main

while(1)
{
     printf("Choice");
     scanf("%i", &MENYVAL);
    switch(MENYVAL){
            case 1 : ADDVEHICLE();      break;
            case 2 : read();            break;
            default: printf("No choice was made");
    }
            printf("\tChoice");
            scanf("%i", &MENYVAL);
}

where "ADDVEHICLE" is the following function

void ADDVEHICLE() {
FILE *fp;
char CAR[50];

fp = fopen("FILE.txt", "a");

if(!fp) {
    printf("ERROR");
}

printf("\n Manufacturer");
fgets(CAR, sizeof(CAR), stdin);
fprintf(fp, "%s", CAR);

fclose(fp);}

When running the program and scanning "MENYVAL=1" I get the output

Manufacturer Choice

I.e the code reads the print in ADDVEHICLE but then returns to the switch code in int main without asking for input.

Attempts: If I remove the switch code and just call the function ADDVEHICLE the code works fine, I can input text which is stored in the correct txt file.

I tested adding after "fprinf" the following code (which i believe tries to flush the buffer) see link for inspiration:

while (!EOF) { fprintf(fp, "%s", "\t");} 

with no success.

PS. I am programming on a linux VM but I am not sure if it is correct to use the tag, I apologize if the tag is incorrect

1 Answers1

2

Probably the '\n' character, remaining after execution of scanf() before switch, is readed inside ADDFORDON() function by fgets() call. Add "buffer flusher" before fgets() like below:

void ADDVEHICLE() {
    FILE *fp;
    char CAR[50];

    fp = fopen("FILE.txt", "a");

    if (!fp) {
        printf("ERROR");
    }

    // flush buffer here!
    scanf("%s"); // this reads any characters remaining in input buffer then ignores them

    printf("\n Manufacturer");

    fgets(CAR, sizeof(CAR), stdin);
    fprintf(fp, "%s", CAR);

    fclose(fp);
}
VillageTech
  • 1,968
  • 8
  • 18