【发布时间】:2016-05-17 23:26:45
【问题描述】:
我的代码有一些问题。起初,当我想从 switch 语句中调用函数时,它不起作用。我的意思是函数正在调用,但 fgets 和 stdin 不起作用。如果我在 main 中单独调用相同的函数,则一切正常。另一个问题是,当我想在 else 语句中调用相同的函数时。我想在密码(或昵称)错误时只调用一次该功能,但它会调用多次,通常是随机的次数。
void passcheck(){
char password[11];
int up,num;
puts("Password (max 10 signs, must contain upperletter and number):");
fgets(password, 10, stdin);
for(int i = 0; i < 10; i++){
if (isupper(password[i])) {
up=1;
}
if (isdigit(password[i])){
num=1;
}
}
if (num == 1 && up == 1){
printf("Your password is good and looks like:\n%s\n", password);
}
else{
puts("Correct you password");
passcheck();
}
}
void nickname(){
char nick[11];
int up,num;
puts("Type your nickname (must contain upperletter):");
fgets(nick, 10, stdin);
for(int i = 0; i < 10; i++){
if (isupper(nick[i])) {
up=1;
}
}
if (num == 1){
printf("Your nickname is good and it is:\n%s\n", nick);
}
else{
puts("Correct nickname");
nickname();
}
}
void what_to_do(){
int number;
puts("What do you want to do?\n 1. Check password \n 2. Check nickname");
scanf("%d", &number);
switch (number) {
case 1:
passcheck();
break;
case 2:
nickname();
break;
default:
puts("Wrong sign!");
break;
}
}
int main(){
what_to_do();
//passcheck();
return 0;
}
【问题讨论】:
-
你输入什么?
-
void what_to_do() 应该是 void what_to_do(void),其他函数也是如此
-
当程序提示您时,您在提示符下究竟输入了什么,然后您究竟看到了什么?
-
fgets(password, 10, stdin);-->fgets(password, 11, stdin);,int up,num;-->int up = 0, num = 0;,nicknameif (num == 1){-->if (up == 1){ -
scanf("%d", &number);-->scanf("%d%*c", &number);或scanf("%d", &number); while(getchar()!='\n');
标签: c function switch-statement