C 中的嵌套 if 语句 - 为什么它不评估最后一个 else if?

Jer*_*ska 3 c if-statement control-flow

else if当您分配给choicevalue时,以下代码不会执行最后一条语句3

#include<stdio.h>
#include<stdlib.h>

int main() {
    puts("Specify with a number what is that you want to do.");
    puts("1. Restore wallet from seed.");
    puts("2. Generate a view only wallet.");
    puts("3. Get guidance on the usage from within monero-wallet-cli.");

    unsigned char choice;
    choice = getchar(); 
 
    if ( choice == '1' ) {
        system("nice -19 ~/monero-x86_64-linux-gnu-v0.17.2.0/monero-wallet-cli --testnet --restore-deterministic-wallet"); 
        exit(0);
    }
    else if ( choice == '2' ) {
        system("nice -19 ~/monero-x86_64-linux-gnu-v0.17.2.0/monero-wallet-cli --testnet --generate-from-view-key wallet-view-only");
        exit(0);
    }
    else if ( choice == '3' ) {    
        puts("Specify with a number what is that you want to do.");
        puts("1. Get guidance in my addresses and UTXOs");
        puts("2. Pay");
        puts("3. Get guidance on mining.");
    
        unsigned char choicetwo = getchar();
        if ( choicetwo == '1' ) {      
            printf("Use \033address all\033 to get all your addresses that have any balance, or that you have generated at this session.");
            printf("Use \033balance\033 to get your balance");
            printf("Use \033show_transfers\033 to get ");
            printf("Use \033show_transfers\033 out to get ");
            printf("Use \033show_transfers in\033 to get your balance");
        }
    }

    return 0;   
}
Run Code Online (Sandbox Code Playgroud)

当我输入时,我得到以下输出3

Specify with a number what is that you want to do.
1. Restore wallet from seed.
2. Generate a view only wallet.
3. Get guidance on the usage from within monero-wallet-cli.
3
Specify with a number what is that you want to do.
1. Get guidance in my addresses and UTXOs
2. Pay
3. Get guidance on mining.
Run Code Online (Sandbox Code Playgroud)

我真的被阻止了,有些东西丢失了,我不知道为什么它不继续第二次接受用户的输入。

dbu*_*ush 6

当您为第一个输入输入“3”时,您实际上是在输入两个字符:字符'3'和换行符。第一个getchar函数从输入流中读取“3”,第二个函数读取换行符。

接受第一个输入后,您需要getchar循环调用,直到读取换行符以清除输入缓冲区。

choice = getchar();
while (getchar() != '\n');
Run Code Online (Sandbox Code Playgroud)