maniteja
maniteja

Reputation: 717

How to scan entire line in php?

I'm trying to scan an entire line but my code takes only the first character and then jumps to the next line. Here is what I'm trying to do:

<?php
$n_matrix_val=4;
for ($y = 1; $y <= $n_matricx_val; $y++) {
   fscanf(STDIN ,"%s\n", $the_matricx_val);
   fwrite(STDOUT, $the_matricx_val);
}

My input is:

5 8 9 7
3 4 9 8
1 5 4 9
3 2 7 6

and my out put is:

5313

I'm very new at this I'm trying solve small problems please help

Upvotes: 3

Views: 413

Answers (3)

krozaine
krozaine

Reputation: 1531

You can also do :

<?php 
    $i=trim(fgets(STDIN));
?>

This code will get you the whole line.

Upvotes: 0

sectus
sectus

Reputation: 15464

Your pattern is worng. Try this.

$n_matrix_val = 4;
for ($y = 1; $y <= $n_matrix_val; $y++)
    {
    $the_matricx_val = fscanf(STDIN, "%s %s %s %s");
    fwrite(STDOUT, implode(' ', $the_matricx_val) . PHP_EOL);
    }

But if you want to read whole line just use fgets.

    $the_matricx_val = fgets(STDIN);
    fwrite(STDOUT, $the_matricx_val);

Upvotes: 3

xdazz
xdazz

Reputation: 160853

Use "%[^\n]s" to get whole line:

$n_matricx_val=4;

for($y=1;$y<=$n_matricx_val;$y++)
{
    fscanf(STDIN ,"%[^\n]s", $the_matricx_val);
    fwrite(STDOUT, $the_matricx_val . "\n");
}

Upvotes: 0

Related Questions