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())
2 Answers
Use std::getline. Extract an entire line from your input stream, and then process each command from that. You will probably want to wrap the output line in an std::istringstream to do that.
Comments
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.
3 Comments
Rubens
@KayTee What do you mean by do that without
./program? How do you want to run your application?Clark
I meant how do you it within the program not in command prompt.
Rubens
@KayTee Well, it depends on what is your input. You must define what is to be passed as argument to your program, so that you can do whatever you want within it. If the case is that you have those
x, y, and z coming from an input file, you simply need to replace the array argv with the array of characters read from your file.