如何使用php命令行在一行中获取多个标准输入

问题描述:

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 ?

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.

Equivalent in PHP would be:

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

$testCase = (int) fgets(STDIN);

while($testCase--) {
    $input = fgets(STDIN);
    $inputParts = preg_split("/[\s]+/",$input);
    $myPosition = (int)$inputParts[0];
    $liftPosition = (int)$inputParts[1];
}

This is because the C-type shift operator in your example takes in both numbers as separate numbers. It delimits automatically with the whitespace character. Therefore you need to split the input string in PHP manually.