0

I am working on a simple script to translate a ROT 13 cipher in php. I wanted to make a looping script that would prompt the user to enter the cipher text, translate it and then continue looping until they pressed no.

For some reason when the loop runs for the second time it completely skips the first input prompt from fgets and goes to the terminating input at the bottom of the file and I cannot figure out why? I have written many programs like this in Java.

Here is the relevant code.

<?php

require('./rot_functions.php');

$input;
$terminate = false;

do {
echo "enter the cipher: \n";

$input = trim(fgets(STDIN));

$convertedString = [];

$input = str_split($input);

foreach ($input as $letter) {
    if (isCaps($letter)) {
        $convertedString[] = processCaps($letter);
    } else if (isLowerCase($letter)) {
        $convertedString[] = processLowerCase($letter);
    } else {
        $convertedString[] = $letter;
    }
}

echo implode($convertedString);

echo " would you like to continue? (y/n) \n";

$input = trim(fgetc(STDIN));

$input === 'y' ?: $terminate = true;

} while (!$terminate);

-- sample console output --
λ php rot13.php
enter the cipher:
Gur cnffjbeq vf 5Gr8L4qetPEsPk8htqjhRK8XSP6x2RHh
The password is 5Te8Y4drgCRfCx8ugdwuEX8KFC6k2EUu would you like to continue? 
(y/n)
 y
 enter the cipher:
 would you like to continue? (y/n)
 y
 enter the cipher:
 would you like to continue? (y/n)
 n
koalamo
  • 199
  • 3
  • 11
  • Which variable have to store previous result? `$convertedString`? – Nikita Leshchev Aug 05 '18 at 09:47
  • yes converted string stores the converted letters, I would like it to be cleared on each new iteration. If I remove the terminating condition (including the second input prompt) from the bottom and let it loop infinitely, the prompt at the top keeps working, – koalamo Aug 05 '18 at 09:48
  • What do you get in `$input` after before setting `$terminate`? Also, try to use following code: `$terminate = $input !== 'y';` – Nikita Leshchev Aug 05 '18 at 09:52
  • I edited my post with some sample output from the terminal – koalamo Aug 05 '18 at 10:00
  • Instead of `fgetc` I would also use `fgets` - otherwhise you could run into trouble with the line breaks. – Philipp Aug 05 '18 at 10:07
  • I actually got it working using the solution from this https://stackoverflow.com/questions/15322371/php-wait-for-input-from-command-line However I'm not sure why fopen works and fgets doesn't? – koalamo Aug 05 '18 at 10:11

0 Answers0