James
James

Reputation: 713

Simple way to read variables on different lines from STDIN?

I want to read two integers on two lines like:

4
5

This code works:

fscanf(STDIN,"%d",$num);
fscanf(STDIN,"%d",$v);

But I wonder if there's a shorter way to write this? (For more variables, I don't want to write a statement for each variable) Like:

//The following two lines leaves the second variable to be NULL
fscanf(STDIN,"%d%d",$num,$v);
fscanf(STDIN,"%d\n%d",$num,$v);

Update: I solved this using the method provided in the answer to read an array and list to assign variables from an array.

Upvotes: 2

Views: 1445

Answers (2)

arkascha
arkascha

Reputation: 42984

Consider this example:

<?php

$formatCatalog = '%d,%s,%s,%d';

$inputValues = [];
foreach (explode(',', $formatCatalog) as $formatEntry) {
  fscanf(STDIN, trim($formatEntry), $inputValues[]);
}

var_dump($inputValues);

When executing and feeding it with

1
foo
bar
4

you will get this output:

array(4) {
  [0] =>
  int(1)
  [1] =>
  string(3) "foo"
  [2] =>
  string(3) "bar"
  [3] =>
  int(4)
}

Bottom line: you certainly can use loops or similar for the purpose and this can shorten your code a bit. Most of all it simplifies its maintenance. However if you want to specify a format to read with each iteration, then you do need to specify that format somewhere. That is why shortening the code is limited...


Things are different if you do not want to handle different types of input formats. In that case you can use a generic loop:

<?php

$inputValues = [];
while (!feof(STDIN)) {
  fscanf(STDIN, '%d', $inputValues[]);
}

var_dump($inputValues);

Now if you feed this with

1
2
3

on standard input and then detach the input (by pressing CTRL-D for example), then the output you get is:

array(3) {
  [0] =>
  int(1)
  [1] =>
  int(2)
  [2] =>
  int(3)
}

The same code is obviously usable with input redirection, so you can feed a file into the script which makes detaching the standard input obsolete...

Upvotes: 2

Kariamoss
Kariamoss

Reputation: 552

If you can in your code, try to implement a array :

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

$num=array();
while($n--){
    fscanf(STDIN, "%d\n", $num[]);
}
print_r($num);

Upvotes: 2

Related Questions