doushua7737 2017-08-11 11:26
浏览 156
已采纳

如何使用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 ?

  • 写回答

2条回答 默认 最新

  • doutou7286 2017-08-11 15:48
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题