简体   繁体   English

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

[英]Nested if statement in C - why doesn't it evaluate the last else if?

The following code does not execute the last else if statement when you assign to choice value 3 .当您分配给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;   
}

I get the following output When I enter 3 :当我输入3时,我得到以下 output :

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.

I'm really blocked, something is missing and I have no clue why it does not proceed to take the input from the user for the second time.我真的被阻止了,有些东西不见了,我不知道为什么它不继续第二次接受用户的输入。

When you enter "3" for the first input, you're actually inputting two characters: the character '3' and a newline.当您为第一个输入输入“3”时,您实际上输入了两个字符:字符'3'和一个换行符。 The first getchar function reads "3" from the input stream, and the second one reads the newline.第一个getchar function 从输入 stream 中读取“3”,第二个读取换行符。

After accepting the first input, you'll want to call getchar in a loop until you read a newline to clear the input buffer.接受第一个输入后,您需要循环调用getchar直到读取换行符以清除输入缓冲区。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM