简体   繁体   中英

how to exit a while loop through a function in C++

Let's assume mf_ptr is a typedef of member function pointer of a class. And we have the flowing code:

map<string, mb_ptr> cmd_table;
cmd_table["exit"] = &class_name::exit;
string cmd;
while (cin >> cmd){
    (this->*cmd_table[cmd])();
}

So how should i define the function exit() to exit the while loop?

You have a few options:

  1. Raise an exception in the exit function, and catch it in the while loop.

  2. Have all your functions return a boolean, whether or not to exit the while loop.

You can do something like this:

while (cin >> cmd && !class_name::exitLoop){
    (this->*cmd_table[cmd])();
}

Where class_name::exitLoop would be set to true by class_name::exit() .

I'd personally go with:

while(cin >> cmd && cmd != "exit") {
    (this->*cmd_table[cmd])();
}

You can use (the way you specified it as above):

class_name::exit(void) { cin.setstate(eofbit); ... }
...
while(cin >> cmd)
    (this->*cmd_table[cmd])();

in which case the loop will terminate after processing the exit command (next iteration round the >> will fail).

If you want to go for a larger amount of complexity, you could create a custom stream extraction operator ,

friend istream & operator>>(istream & is, class_name::CmdExecutorClass &comm)
{
    string cmd;
    cin >> cmd;
    if (cmd == "exit")
        cin.setstate(eofbit);
    else
        (comm.table[cmd])();
    return is;
}

The advantage of that I can see is that you could simply write:

while (cin >> cmd);

and you could handle errors / unknown commands (eg std::map<...>::operator[] adds to the map if no element exists for the key - that may not be what you want).
But you also need quite some glue to create the CmdExecutor class (constructor or templating to pass the table[] reference in from the embedding "master" class, ...). For a simple case, overkill.

Edit: Should also add that closing cin (that's what setting the eof bit does, effectively) may be unwanted as well. The fail bit (which could be cleared again afterwards) is probably a better option.

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