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

标签 c if-statement control-flow

当您分配给 choice3 时,以下代码不会执行最后一个 else if 语句。

#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;   
}

当我输入 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.

我真的被阻止了,缺少了一些东西,我不知道为什么它不继续第二次从用户那里获取输入。

最佳答案

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

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

choice = getchar();
while (getchar() != '\n');

关于c - C 中的嵌套 if 语句 - 为什么它不评估最后一个 else if?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68866548/

相关文章:

c - 在读取共享变量之前需要锁定吗?

c++ - 如果缩小分配的内存大小,还要检查 realloc() 吗?

python - 如何设置 if 语句以使用条件数组作为 python 中的输入

Python - 多个if语句被忽略

algorithm - 控制流异常

c - 查找两个文件不同的所有字节位置

C:strcpy 的段错误

Ruby - 退出 IF block

language-agnostic - 编程 101,如果 block 选择 VS

java - 无需两次检查值即可表达此 Java 条件的最简洁方法