如何以正确的方式重复是或否选项?

问题描述

在这代码中,我面临两个问题。 一个问题是每当我尝试选择 y 再次重复该过程时,它都会给我一个类似

的选项
Enter a word: Enter word: (Taking first input and duplicating that input to the second one also)
Enter a word: (Taking third input)

但是我希望它能给我像

Enter a word:
Enter a word:
Enter a word:

第二个问题是我想使用 fgets(),但是它不起作用。

代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
  FILE *fw = fopen("new.csv","a");
  char data[3][21],input[20],option;
  do {  
    for (int i=0; i<3; i++) {
      printf("Enter a word: ");
      fgets(data[i],20,stdin);
      fprintf(fw,"%s %s %s",data[0],data[1],data[2]);
    }
    printf("Do you want to continue [y/n]: ");
    scanf("%s",&option);
    // fgets(option,10,stdin);
  } while (option == 'y');

  return 0;  
}

解决方法

Fgets将获得换行符,因为您看到它以所看到的格式输入单词。您可以通过更改代码来解决此问题。我也更改了fprintf函数的位置。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int main() {
FILE *fw = fopen("new.csv","a");
char data[3][21],input[20],option;

 do {  
    for (int i=0; i<3; i++) {
    printf("Enter a word: ");
    fgets(data[i],20,stdin);
    if(strcmp(data[i],"\n")==0)
     fgets(data[i],stdin);    
   }
 fprintf(fw," %s %s %s",data[0],data[1],data[2]);
 printf("Do you want to continue [y/n]: ");
 scanf("%c",&option);
 // fgets(option,10,stdin);
  } while (option == 'y');

return 0;  
}`