Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 5578

General • Re: C program, flush input, scanf(), menus, etc.

$
0
0

Code:

// Main menu state-handler functionvoid mainMenu() {    int choice;    printf("\nEnter your choice: ");    if (scanf("%d", &choice) == 1) {    switch (choice) {        case 1:            currentState = doThings;            break;        case 2:            currentState = doOtherThings;            break;        default:            // handles numbers that not 1-4 OK            printf("Invalid choice. Please try again.\n");            break;    }    }    else {    printf("HALT!");    while(1); // loop forever so serial doesn't loop menu forever    // Instead need to deal with the bad character somehow    }
You don't necessarily have to convert the input to a number, can't you read the input as a character and then in the switch statement use '1', '2', etcetera?

Example shamelessly copied from here:

Code:

int main() {    char i,a = 0;    printf("Write something:");    scanf("%c", &i);    do{        switch (i)        {        case '1':        case '2':        case '3':        case '4':        case '5':            printf("%c",i);            break;        case 'e':            a=1;            break;        default:            printf("This is not a number");             break;        }    }while (a==0);}

Statistics: Posted by jj_0 — Fri Apr 05, 2024 9:18 am



Viewing all articles
Browse latest Browse all 5578