for(;;) vs do..while() for main program loop

for(;;) vs do..while() for main program loop

本文关键字:for program loop main vs do while      更新时间:2023-10-16

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

主.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发送数据的程序。我只是在寻找一些关于如何安全退出该程序的建议。

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