0

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;
}
  • There is no check if the input is digit. – BLUEPIXY Feb 23 '14 at 20:08
  • You are looking for [this](http://stackoverflow.com/questions/717572/how-do-you-do-non-blocking-console-i-o-on-linux-in-c)? – joy Feb 23 '14 at 20:13
  • @BLUEPIXY sorry, I'm doing the check afterwards with a switch case that accepts only a value of foo of 1, 2 or 3. – beachcabana Feb 23 '14 at 20:19
  • @neagoegab I don't think so – beachcabana Feb 23 '14 at 20:19
  • you can use scanf("%1d", &foo)... – joy Feb 23 '14 at 20:25
  • @neagoegab that doesn't handle the 'single' digit part. If I input "123" it counts as three different inputs. – beachcabana Feb 23 '14 at 20:34
  • 2
    Use `fgets()` to read a whole line. Then, make sure you only have one digit in your input. You decide if you will accept the input or not by adding the appropriate code. – jxh Feb 23 '14 at 20:40
  • @jxh That was my first aproach but it took me 5 lines of code so it was more complicated. – beachcabana Feb 23 '14 at 20:43
  • For the fgets solution, you need only 3 bytes: one for the digit, one for the newline if it is present, and one for the null terminator. If the newline isn't present, it will be a null terminator if you read a single digit. Otherwise, you have more than just the one digit, if there is even a digit at all. The getchar solution works, but you must be sure that the next getchar call returns '\n' or EOF. Otherwise, you don't have just a single digit. –  Feb 23 '14 at 20:46
  • 2
    Use jxh's approach and make it into a function. Then you can use it everywhere and future improvements are seen by all callers. And five lines of code in a separate functzion will not make the client code, i.e where you use it, more complicated. Something like `n = getdigit()` will make it even more readable. – M Oehm Feb 23 '14 at 20:48
  • What I was aiming for was less code but I guess that doesn't necessarily mean more simplicity. I see now how the fgets solution is the simplest approach. Thank you for your help everyone. – beachcabana Feb 23 '14 at 21:03
  • Also, you can use `isdigit(foo)` to check `foo` is a digit (0 - 9) – Younggun Kim Feb 23 '14 at 21:25
  • @beachcabana, yup it will but you can use getchar to drop all remaining digits/characters including new line. – joy Feb 24 '14 at 08:34

1 Answers1

2

This is how it goes in C :

scanf("%1d",&varname);
KJ Sudarshan
  • 2,694
  • 1
  • 29
  • 22