使用两个scanf()函数分别获取保存文件的选择和是否继续的选择的字符串,然后使用strcmp()函数来判断选择即可,修改如下:
参考链接:
C 库函数 – strcmp() | 菜鸟教程
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
char name[20];
char sex[20];
int age;
int height;
}Cominfo;
int main(void){
FILE * fp;
char fileName[20];
Cominfo ci;
char continueChoice[10]="y";
char saveChoice[10];
printf("请创建个文件进行保存:\n");
scanf("%s",fileName);
fp = fopen(fileName,"w");
// https://www.runoob.com/cprogramming/c-function-strcmp.html
while(strcmp(continueChoice,"y")==0){
printf("请输入用户名:\n");
scanf("%s",ci.name);
printf("请输入用户性别:\n");
scanf("%s",ci.sex);
printf("请输入用户年龄;\n");
scanf("%d",&ci.age);
printf("请输入身高;\n");
scanf("%d",&ci.height);
printf("确认保存(y/n):\n");
scanf("%s",saveChoice);
if(strcmp(saveChoice,"y")==0){
fprintf(fp,"用户名:%s\n性别:%s\n年龄:%d\n身高:%d\n",
ci.name,ci.sex,ci.age,ci.height);
}
printf("是否需要继续输入(y/n):\n");
scanf("%s",continueChoice);
}
fclose(fp);
}