beachcabana
beachcabana

Reputation: 1

Getting a single digit of user input

I'm a begginer and this is my first post so go easy on me :)

Is there a better way of getting a single digit of user input, repeatedly? The input should consist only in a single digit followed by the return key.

for (int i = 0; i < n; i++)
{
    int foo = getchar() - '0';
    if (foo == '\n' - '0' || getchar() != '\n')
        return 1;
}

Thanks in advance

Paulo Ribeiro

EDIT: After the loop I'm doing the following check.

switch (foo)
{
    case 1:
        //do something
    case 2:
        //do something
    case 3:
        //do something
    default:
        return 1;
}

Upvotes: 0

Views: 2497

Answers (1)

KJ Sudarshan
KJ Sudarshan

Reputation: 3222

This is how it goes in C :

scanf("%1d",&varname);

Upvotes: 2

Related Questions