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 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探