PHP阅读fscanf

时间:2019-02-28 17:18:51

标签: php scanf

我一直在尝试从在线课程中读取带有STDIN输入的数字,而我的文件是这样的:

2
3 15

我读了2和3,怎么读15?

我的代码:

    <?php
    /*
    // Sample code to perform I/O:

    fscanf(STDIN, "%s\n", $name);           // Reading input from STDIN
    echo "Hi, ".$name.".\n";                // Writing output to STDOUT

    // Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
    */

    // Write your code here
    fscanf(STDIN, "%s\n", $ammount);
    echo $ammount . "\n";
    for ($i = 0; $i <= $ammount; $i++)
{
    fscanf(STDIN, "%s", $x);
    echo $x . "\n";
}
    ?>

我现在的输出是:2 3 3并且我想要2 3 15

2 个答案:

答案 0 :(得分:0)

fscanf在行上有效,但是默认情况下,%s在空间上停止读取。使用:

fscanf(STDIN, "%[^\n]", $x);

并用空格爆炸$x

答案 1 :(得分:0)

我要带您去的是在格式字符串中使用空格,然后将输入读入单独的变量,像这样。

fscanf(STDIN, "%s %s", $a, $b);
echo $a . ' ' . $b . "\n";
相关问题