3
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 ?

1
  • This is not a c++ question... Commented Aug 11, 2017 at 12:27

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@TheExtendable You're welcome! Remember to accept correct answers and upvote helpful comments and answers.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.