doujun5009 2019-05-02 08:40
浏览 24
已采纳

如何检查shell中正确的STDIN用户输入量?

I'm trying to solve a problem where you write a script and then get:

  1. multiple test cases with 5 integer user inputs
  2. one test case with one single 0

I want to check the number of user inputs and then determine which code is executed.

Something like this:

if(fscanf(STDIN, '%d%d%d%d%d', $a, $b, $c, $d, $e) == 5) {
        echo "Five inputs";
    } elseif(fscanf(STDIN, '%d', $a) == 1) {
        echo "Only one input";
    }

So if you get for example the input 1 2 3 4 5 it should echo "Five inputs" but if you only get 0 it should echo "Only one input".

  • 写回答

1条回答 默认 最新

  • douye2036 2019-05-02 08:49
    关注

    There are a couple of problems with your code. The first is that you scan using %d%d%d%d%d, this is looking for a continuous number, you would at least have to have spaces in there to delimit the values. The second is that if this fails, it will ask for input again for the single input check.

    This code reads a line from the input and then splits it (using explode()) into parts. Te middle bit just checks for numerical values and you can adjust this if needed. Then the last part just checks how many parts there are (using count($inputs)) and outputs the appropriate message.

    $input = fgets(STDIN);
    $inputs = explode(" ", $input);
    // Check numeric
    foreach ( $inputs as $index => $check )   {
        if ( !is_numeric($check) )  {
            echo "Input $index is not numeric".PHP_EOL; 
        }
    }
    if(count($inputs) == 5) {
        echo "Five inputs";
    } elseif(count($inputs) == 1) {
        echo "Only one input";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥15 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)