我有一个简单的C语言电话簿,它将输入信息保存到我的电脑上的文本文件中。C电话簿程序:如何退出避免无限循环以及如何返回到switch语句菜单
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
void validateName(char name[], FILE *fptr);
void validateID(char id[], FILE *fptr);
void validateScore(int score, FILE *fptr);
void addContact(char name[], char id[], int score, FILE *fptr);
void printContact(FILE *fptr);
void printAll();
int main()
{
char name[30], id[10];
int score;
int i;
FILE *fptr;
fptr = fopen("C:\\c\\program.txt","w");
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
else {
bool flag = true;
do{
printf("\n1. Press 1 to display record\n"
"2. Press 0 to add a new contact\n"
"3. Press -1 to display all records\n\n");
int option;
scanf("%d", &option);
switch(option) {
case 1:
printContact(fptr);
flag = false;
break;
case 0:
addContact(name, id, score, fptr);
flag = false;
break;
case -1:
printAll();
flag = false;
break;
default:
printf("wrong choice, try again\n\n");
}
} while(flag);
fclose(fptr);
return(0);
}
}
void validateName(char name[], FILE *fptr){
bool flag = true;
while(flag){
fgets(name, 30, stdin);
if ((strlen(name) < 3) || (strlen(name) > 20)) {
printf("error\nplease enter name again: ");
} else {
flag = false;
}
}
}
void validateID(char id[], FILE *fptr){
bool flag = true;
while(flag) {
if (!isalpha(id[0])){
printf("enter a letter as first char\n");
}
else if(strlen(id) > 10) {
printf("error too much numbers \n");
} else {
flag = false;
}
}
}
void validateScore(int score, FILE *fptr) {
if(score >= 0 && score <= 100) {
fprintf(fptr, "SCORE: %d\n", score);
} else {
printf("invalid input");
(exit(1));
}
}
void addContact(char name[], char id[], int score, FILE *fptr) {
//first name
printf("Enter name: ");
scanf("%s", name);
validateName(name, fptr);
fprintf(fptr,"NAME: %s \n", name);
//id
printf("Enter id: ");
scanf("%s", id);
validateID(id, fptr);
fprintf(fptr,"STUDENT NO: %s\n", id);
//score
printf("enter score: ");
scanf("%d", &score);
validateScore(score, fptr);
}
void printContact(FILE *fptr) {
int c;
char contacts[50];
while((c = getchar()) != EOF) {
fscanf(fptr, "%s", &contacts);
for(int i = 50; i < 50; i++){
printf("%s", &contacts);
}
}
}
void printAll() {
}
我的第一个问题是validateID函数中: 我一直陷入无限循环,当我尝试验证的首要条件,这是确保第一个索引是一个字符。
我的第二个问题是,当我输入姓名,学号和分数时,程序结束,我不回到菜单切换语句以选择其他选项?
我在做什么错,或者我错过了什么?
我和循环如果第一个字符非字母,如果有以下的第一个字母小于9个的数字。所以如果这些条件不满足,循环应该显示一个错误,并要求用户重新输入一个字母或重新输入一个有效的数字 – Rgoat
我将如何重新初始化switch语句中的标志? – Rgoat
你需要告诉计算机做你想做的事情。你的设计不适合做你想做的事情 - 我已经指出了你的程序为什么不起作用,作为编程人员来决定如何解决这个问题是由你来决定的,因为它是一个设计问题,反对一个特定的bug。 – Caleb