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

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

like Input is:
3
1 2
2 3
4 5

我必须以给定的方式接受这些输入。这里(1和2),(2和3)和(4和5)必须接受一行作为输入。

这是我的代码片段。

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

$testCase = (int) fgets(STDIN);

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

C++ 中的实现

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

   cin >> testcase;

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

那么,如何实现PHP中的C++代码呢?

PHP 中的等价物是:

<?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];
}

这是因为您示例中的 C 型移位运算符将两个数字作为单独的数字。它自动用空白字符定界。因此,您需要手动拆分 PHP 中的输入字符串。

其实问题出在下面一行:

$myPosition = (int) fgets(STDIN);

在这里,显式转换为 int 是丢弃 space 之后的值,因此当您在命令行中将 1 2 作为输入时,(int) 会将其转换为 1 而你正在失去另一个角色。

$arr = [];
$testCase = (int) fgets(STDIN);

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

print_r($arr);

上述解决方案有效,因为我从 fgets 的开头删除了 (int)。另请注意,我在这里使用 list($a, $b),这实际上会在当前范围内创建两个变量 $a and $b,所以我总是假设,您将使用两个单独的数字(即:1 2 ), 否则你可以使用 $inputParts = preg_split("/[\s]+/",$input) 或其他带有 explode 的东西来从控制台的输入中形成数组。