1

The code is working fine but whenever I type the words second time and it comes to seeing the result in a file, it gives me the result like this. How to handle this?

Name, DOB, ID, Phone 
Name
, DOB, ID, Phone

The Code

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LEN 50

int main(){
  FILE * fw = fopen("new.csv", "a");
  char* listing[] = {"Name", "Date of birth","ID card number","Phone number"};
  char data[4][LEN], name[LEN], amount[LEN], dob[LEN], id[LEN], option; 
  int i, done=0;
  do{
    for (i = 0; i < 4; i++) {
    printf("Enter your %s: ", listing[i]);
    fgets(data[i], LEN, stdin);
    if(strcmp(data[i], "\n") == 0){
      fgets(data[i], LEN, stdin);
    }
    else{
      data[i][strlen(data[i])-1] = '\0';         
    }
  }
  fprintf(fw, "%s, %s, %s, %s\n", data[0], data[1], data[2], data[3]);
  printf("Do you want to continue [y/n]: ");
  scanf("%s", &option);
}
  while(option == 'y');
  fclose(fw);
return 0;
}

1 Answers1

0

Try this:

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#define LEN 50

int main() {
    FILE * fw = fopen("new.csv", "a");
    char * listing[] = {
        "Name",
        "Date of birth",
        "ID card number",
        "Phone number"
    };
    char data[4][LEN], name[LEN], amount[LEN], dob[LEN], id[LEN], option;
    int i, done = 0;
    do {
        for (i = 0; i < 4; i++) {
            printf("Enter your %s: ", listing[i]);
            fgets(data[i], LEN, stdin);
            while (strcmp(data[i], "\n") == 0) {  //<------Changed if condition to while loop
                fgets(data[i], LEN, stdin);
            }
            data[i][strlen(data[i]) - 1] = '\0';
        }
        fprintf(fw, "%s, %s, %s, %s\n", data[0], data[1], data[2], data[3]);
        printf("Do you want to continue [y/n]: ");
        scanf("%s", & option);
    }
    while (option == 'y');
    fclose(fw);
    return 0;
}

I changed the if statement to while loop where you checked if input is '\n'.

thisisjaymehta
  • 614
  • 1
  • 12
  • 26