代码运行良好,但是每当我第二次键入单词时,就可以看到文件中的结果,它给了我这样的结果。如何处理呢?
Name, DOB, ID, Phone
Name
, DOB, ID, Phone
编码
#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;
}
尝试这个:
#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;
}
我将if语句更改为while循环,在其中检查输入是否为'\n'
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句