首页 > 解决方案 > 在 PHP 中为用户输入的 wair 执行 while 循环?

问题描述

我正在编写一个简单的脚本来翻译 php 中的 ROT 13 密码。我想制作一个循环脚本,提示用户输入密文,翻译它,然后继续循环,直到他们按下否。

由于某种原因,当循环第二次运行时,它完全跳过了 fgets 的第一个输入提示并转到文件底部的终止输入,我不知道为什么?我用 Java 写过很多这样的程序。

这是相关的代码。

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

标签: phpwhile-loopscripting

解决方案


推荐阅读