【问题标题】:Can't call a function properly from switch, can't recall a function无法从开关正确调用函数,无法调用函数
【发布时间】: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;, nickname if (num == 1){ --> if (up == 1){
  • scanf("%d", &amp;number); --> scanf("%d%*c", &amp;number);scanf("%d", &amp;number); while(getchar()!='\n');

标签: c function switch-statement


【解决方案1】:

您所有的问题都与标准输入的输入处理方式有关:它被处理为字符流,而只有当您按下回车键时才会从终端发送数据,该键会添加一个新的行字符流。

您的代码不需要换行符并将其解释为输入的一部分,这会导致所解释的副作用。

每次从标准输入读取时,都必须消耗或删除换行符。这里详细解释了为什么会发生这种情况以及您可以采取哪些措施来避免这种情况:

http://www.gidnetwork.com/b-60.html

【讨论】:

  • 另外:每当您需要调试代码时,最好将输入转储您将要处理的内容。如果您在读取密码后将此行添加到代码中:printf("input: '%s'", password);,那么您会立即看到新行字符已添加到您的输入提要中。
  • ^^ @racs 所说的。这叫做调试。如果不能调试,就不能对计算机进行编程。
猜你喜欢
  • 1970-01-01
  • 2023-04-05
  • 2017-02-21
  • 1970-01-01
  • 2011-09-21
  • 1970-01-01
  • 1970-01-01
  • 2020-02-13
相关资源
最近更新 更多