简体   繁体   中英

multiple word commands C++

I'm a little new to C++, so sorry if this question is obvious, but I've hit a bit of a roadblock. The thing I want to do is have a command prompt that does certain things. You put in simple commands like timer down 10 which will start a timer count down which I have done fine. The way I'm detecting for each word is with this:

string cmd1;
string cmd2;
int cmd3;
cin >> cmd1 >> cmd2 >> cmd3;

That works fine, except I want to have single-word commands and with this system, I can't really do that. If I want, for example, help as a command, its making me type 2 strings and an int when I only want to type 1 string. But I want to have specific commands that can be the full 2 strings and an int or just 1 string.

You need to read the command with getline then split it to tokens. Check for the getline function, and google for split line to tokens c++ .

Use getline to store whole command in a single String.

String command;
std::getline (std::cin,command);

Now, you can split the command into token words using following code.

int counter =0;
string words[10];
for (int i = 0; i<command.length(); i++){
    if (command[i] == ' ')
        counter++;
    else
        words[counter] += command[i];
}

You could read the input line by line and then split each line into a std::vector containing each command followed by its arguments:

void command_help()
{
    // display help
}

void command_timer(std::string const& ctrl, std::string const& time)
{
    int t = std::stoi(time);

    // ... etc ...
}

int main()
{
    // read the input one line at a time
    for(std::string line; std::getline(std::cin, line);)
    {
        // convert each input line into a stream
        std::istringstream iss(line);

        std::vector<std::string> args;

        // read each item from the stream into a vector
        for(std::string arg; iss >> arg;)
            args.push_back(arg);

        // ignore blank lines
        if(args.empty())
            continue;

        // Now your vector contains

        args[0]; // the command
        args[1]; // first argument
        args[2]; // second argument
        // ...
        args[n]; // nth argument

        // so you could use it like this

        if(args[0] == "help")
            command_help(); // no arguments
        else if(args[0] == "timer")
        {
            if(args.size() != 3)
                throw std::runtime_error("wrong number of arguments to command: " + args[0]);

            command_timer(args[1], args[2]); // takes two arguments
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM