在c ++中从一行输入读取多个命令 [英] Reading multiple commands from one line of input in c++

查看:275
本文介绍了在c ++中从一行输入读取多个命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说出输入可以是'x','y'和'z',并且对于每个commandX(),commandY()和commandZ()可以分别执行。而不是必须键入,然后按enter键每次(即:x(enter)commandX()执行然后y(enter)commandY()执行...)我如何让用户输入它只有一行(即:xyz (enter)),然后命令按照它们的输入顺序连续进行? (即:在x,y,z中,执行顺序将是commandX()then commandY()then commandZ())

解决方案

p>您最有可能需要 getopt 。 p>

然而,你可以用while循环来实现相同的结果 - 害羞的一些功能 -

  unsigned int i(1); 
bool run_x(false),run_y(false),run_z(false);

while(i
switch(argv [i + 1]){

case'x':
run_x = true;
i + = 2;
break;

case'y':
run_y = true;
y_value = argv [i + 1];
i + = 3;
break;

case'z':
run_z = true;
i + = 2;
break;

}

}

的程序可以执行如下:

  ./ program -x -y 10 -z 
./program - x -z
./program -z
./program -y 10 -z
...

使用布尔值和其他变量来控制/是不是可选的。


Say input can be 'x','y' and 'z' and for each commandX(),commandY() and commandZ() can be executed, respectively. Instead of having to type then pressing enter each time (ie: x (enter) commandX() executed then y (enter) commandY() executed ...) how can I let the user input it into just one line (ie: x y z (enter)) and then the commands are made consecutively in the order of their input? ( ie: in x , y , z the order of execution will be commandX() then commandY() then commandZ())

解决方案

You are most probably looking for getopt.

Yet, you can achieve the same result -- being shy some features --, with a while loop:

unsigned int i(1);
bool run_x(false), run_y(false), run_z(false);

while (i < argc and argv[i] == '-') {

    switch (argv[i + 1]) {

        case 'x':
            run_x = true;
            i += 2;
            break;

        case 'y':
            run_y = true;
            y_value = argv[i + 1];
            i += 3;
            break;

        case 'z':
            run_z = true;
            i += 2;
            break;

     }

}

And the execution of the program could be performed like:

./program -x -y 10 -z
./program -x -z
./program -z
./program -y 10 -z
...

Use the booleans and other variables to control what is/is not optional.

这篇关于在c ++中从一行输入读取多个命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆