Search code examples
phpstdin

How to take multiple standard input in a single line using php command line


like Input is:
3
1 2
2 3
4 5

I have to take those input in given style. Here (1 and 2), (2 and 3) and (4 and 5) have to take in one line as a input.

Here is my code snippet.

 <?php
header('Content-Type: text/plain');

$testCase = (int) fgets(STDIN);

while($testCase--) {
    $myPosition = (int) fgets(STDIN);
    $liftPosition = (int) fgets(STDIN);
}

Implementation in C++

int main()
{
   int testcase, myPos, liftPos;

   cin >> testcase;

   while(testcase--)
   {
      cin >> myPos >> liftPos;
   }
}

So, how can implement the C++ code in PHP ?


Solution

  • Actually, the problem is in the following line:

    $myPosition = (int) fgets(STDIN);
    

    Here, the explicit conversion to int is discarding the value after space, so when you give 1 2 as the input in the command line the (int) is turning it into 1 and you are losing the other character.

    $arr = [];
    $testCase = (int) fgets(STDIN);
    
    while ($testCase--) {
        list($a, $b) = explode(' ', fgets(STDIN));
        $arr[] = $a.' '.$b;
    }
    
    print_r($arr);
    

    The above solution works because I've removed the (int) from the beginning of the fgets. Also note that, I'm using list($a, $b) here, which will actually create two variable $a and $b in the current scope so I'm always assuming that, you'll use two separate numbers (i.e: 1 2), otherwise you can use $inputParts = preg_split("/[\s]+/",$input) or something else with explode to form the array from input from console.