Search code examples
cinputstreamuser-inputvariable-length

Reading various inputs from stdin


I'm reading from the stdin. The user is promoted to eather type one digit or to type three. Which functions are good this problem?

I have tried

    int in[3] = {-1, -1, -1};
    scanf("%d %d %d", &in[0], &in[1], &in[2]);
    printf("%d, %d, %d\n", in[0], in[1], in[2]);

This works great for three digits but not if only one is typed.

I want to have e.g. the input to be "17" or "0 1 9" The output should be then e.g.

int amount = 1
int digits[3] = {17, -1, -1}

or

int amount = 3
int digits[3] = {0, 1, 9}

Solution

  • You are close to what you want, but you read int rather than string so

     char *in[3] = {-1, -1, -1};
    

    must be

    int in[3] = {-1, -1, -1};
    

    also allowing to have -1 as valid initial values.

    This works great for three digits but not if only one is typed.

    doing scanf("%d %d %d", &in[0], &in[1], &in[2]); to finish you need to enter 3 valid int or to finish on erro ro reach EOF or give invalid input, to be able to only enter one value do a fgets then _a __sscanf_

    I want to have e.g. the input to be "17" or "0 1 9" The output should be then e.g.

    int amount = 1
    int digits[3] = {17, -1, -1}
    

    or

    int amount = 3
    int digits[3] = {0, 1, 9}
    

    do for instance

    #include <stdio.h>
    
    int main(void)
    {
      char line[32];
    
      if (fgets(line, sizeof(line), stdin) == line) {
        int ints[3] = { -1, -1, -1 };
        int amount = sscanf(line, "%d %d %d", &ints[0], &ints[1], &ints[2]);
    
        printf("%d : { %d %d %d }\n", amount, ints[0], ints[1], ints[2]);
      }
    
      return 0;
    }
    

    Compilation and executions

    pi@raspberrypi:/tmp $ gcc -pedantic -Wall -Wextra c.c
    pi@raspberrypi:/tmp $ ./a.out
    pi@raspberrypi:/tmp $ ./a.out
    17
    1 : { 17 -1 -1 }
    pi@raspberrypi:/tmp $ ./a.out
    0 1 9
    3 : { 0 1 9 }
    pi@raspberrypi:/tmp $ ./a.out
    1 a
    1 : { 1 -1 -1 }
    pi@raspberrypi:/tmp $ ./a.out
    a
    0 : { -1 -1 -1 }
    pi@raspberrypi:/tmp $ 
    pi@raspberrypi:/tmp $ ./a.out
    
    -1 : { -1 -1 -1 }
    pi@raspberrypi:/tmp $ 
    

    (in the last case is an empty line, e.g. just enter)

    I renamed digits to ints because digits let suppose each entry is a digit ('0' for instance) while you want integers