I'm using a do..while loop to allow my program to exit if a condition is correct, but I've seen in examples when I was in school where an exception was thrown in order to quit. Those examples used a regular infinite for loop. I'm thinking that I could use an if statement to break from the for loop rather than throwing, but I'm not sure. Code below:
// 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;
}
// commands.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
// commands.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 (){
}
Edit: Have included more source. I have lots of blanks because I'm rewriting a program that sends data via UDP. I'm just looking for some recommendations as to how to quit the program safely.