首页 > 解决方案 > for(;;) vs do..while() 用于主程序循环

问题描述

我正在使用 do..while 循环来允许我的程序在条件正确时退出,但是我在学校的示例中看到了抛出异常以退出的示例。这些示例使用了常规的无限 for 循环。我在想我可以使用 if 语句来打破 for 循环而不是抛出,但我不确定。下面的代码:

// main.cpp

#include <cstdlib>
#include <iostream>
#include <string>

#include "commands.h"

using namespace std;

int main(int argc, char *argv[]) {
    bool exit = false;

    try {
        do {
            try {
                // Read a line, break at EOF, and echo print the prompt
                // if one is needed.
                string line;
                getline(cin, line);
                if (cin.eof()) {
                    cout << endl;
                    break;
                }

                command_fn fn = find_command_fn(line);
                fn();
            }
            catch (command_error& error) {
                // If there is a problem discovered in any function, an
                // exn is thrown and printed here.
                cout << error.what() << endl;
            }
        } while (!exit);
    }
    catch (exception& e) {

    }

    return 0;
}

// 命令.h

#ifndef __COMMANDS_H__
#define __COMMANDS_H__

#include <unordered_map>
using namespace std;


// A couple of convenient usings to avoid verbosity.

using command_fn = void (*)();
using command_hash = unordered_map<string,command_fn>;

// command_error -
//    Extend runtime_error for throwing exceptions related to this 
//    program.

class command_error: public runtime_error {
   public: 
      explicit command_error (const string& what);
};

// execution functions -

void fn_connect     ();
void fn_disconnect  ();
void fn_test        ();
void fn_exit        ();

command_fn find_command_fn (const string& command);


#endif

// 命令.cpp


#include "commands.h"

command_hash cmd_hash {
   {"c"  , fn_connect   },
   {"d"  , fn_disconnect},
   {"t"  , fn_test      },
   {"e"  , fn_exit      },
};

command_fn find_command_fn (const string& cmd) {
   // Note: value_type is pair<const key_type, mapped_type>
   // So: iterator->first is key_type (string)
   // So: iterator->second is mapped_type (command_fn)
   const auto result = cmd_hash.find (cmd);
   if (result == cmd_hash.end()) {
      throw command_error (cmd + ": no such function");
   }
   return result->second;
}

command_error::command_error (const string& what):
            runtime_error (what) {
}

void fn_connect (){
}

void fn_disconnect (){
}

void fn_test (){
}

void fn_exit (){

}

编辑:已包含更多来源。我有很多空白,因为我正在重写一个通过 UDP 发送数据的程序。我只是在寻找一些关于如何安全退出程序的建议。

标签: c++

解决方案


do...while完全等同于for循环,只是测试是在循环结束而不是开始时完成的,所以 ado...while总是至少运行一次。在这两种情况下,您都可以使用 退出循环break。您不需要抛出异常,但当然可以。如果您有多个级别,通常更容易抛出异常并在循环中捕获它并中断,或者设置终止条件,或者在循环外捕获异常,这也将终止它。


推荐阅读