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

Viewed 86

The following code does not execute the last else if statement when you assign to choice value 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;   
}

I get the following output When I enter 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.

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.

1 Answers

When you enter "3" for the first input, you're actually inputting two characters: the character '3' and a newline. The first getchar function reads "3" from the input stream, and the second one reads the newline.

After accepting the first input, you'll want to call getchar in a loop until you read a newline to clear the input buffer.

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