Search code examples
phpstdin

How to read a line of numbers in php with fscanf


I am using input from STDIN

A first line is a number that I store in $t

fscanf(STDIN, "%s\n", $t);

The second line is two integers

I don't know how to store them in an array.

If I do

fscanf(STDIN, "%s\n", $n[]);

I get an array with just the first value. I don't know what I am doing here, thank you


Solution

  • it's probably easier to

    $n = fscanf(STDIN, "%d %d\n");
    

    see examples at https://php.net/fscanf (description of parameters at https://php.net/sprintf)

    $n will be an array then. if you need separate values, either use the standard syntax fscanf(STDIN, "%d %d\n", $value1, $value2) or use the list syntax: list($value1, $value2) = fscanf(STDIN, "%d %d\n")

    I would prefer the return values, because it seems semantically more intuitive, but it's probably just a preference / taste.