021
15.03.2005, 21:25 Uhr
0xdeadbeef
Gott (Operator)
|
OK, ich bin noch mal drübergegangen, und ich denke, jetzt ist es so reif, dass ich es benutzen würde - wenn ich denn Textmenüs bräuchte... Here goes:
C++: |
#include <iostream> #include <sstream> #include <string> #include <utility> #include <vector>
class menu_choice { public: virtual ~menu_choice() { };
virtual bool operator()() const = 0;
static const bool GO_BACK = true; };
class menu : public menu_choice { public: menu(std::string const &banner = "", bool offer_back = false, std::string const &back_label = "Zurück") : banner_ (banner ), offer_back_(offer_back), back_label_(back_label) { }
void push_back(std::string const &label, menu_choice *mc) { choices_.push_back(std::pair<std::string, menu_choice const*>(label, mc)); }
virtual bool operator()() const { std::string zeile; std::stringstream sstr; int choice;
do { std::cout << std::endl << banner_ << std::endl << std::endl;
for(int i = 0; i < choices_.size(); ++i) std::cout << i + 1 << ") " << choices_[i].first << std::endl; if(offer_back_) std::cout << choices_.size() + 1 << ") " << back_label_ << std::endl;
do { sstr.clear(); std::getline(std::cin, zeile); sstr.str(zeile); sstr >> choice; } while(!sstr || choice < 1 || choice > choices_.size() + (offer_back_ ? 1 : 0)); if(choice == choices_.size() + 1) return GO_BACK; } while(GO_BACK == (*choices_[choice - 1].second)());
return !GO_BACK; }
private: std::string banner_; bool offer_back_; std::string back_label_; std::vector<std::pair<std::string, menu_choice const*> > choices_; };
class echo : public menu_choice { public: echo(std::string const &msg) : msg_(msg) { }
virtual bool operator()() const { std::cout << msg_ << std::endl; return !GO_BACK; }
private: std::string msg_; };
class main_menu : public menu { public: main_menu(std::string const &banner = "Hauptmenü") : menu(banner) { menu_de = new menu("Deutsch", true); menu_en = new menu("English", true, "Go back"); menu3 = new menu("Menü 3");
hurra = new echo("Hurra!"); hooray = new echo("Hooray!");
menu3->push_back("Hurra", hurra); menu3->push_back("Hooray", hooray); menu3->push_back("Hauptmenü / Main Menu", this);
menu_en->push_back("Menu three", menu3); menu_en->push_back("Hooray!", hooray); menu_de->push_back("Menü drei", menu3); menu_de->push_back("Hurra", hurra); push_back("Deutsch", menu_de); push_back("English", menu_en); }
~main_menu() { delete menu_de; delete menu_en; delete menu3; delete hurra; delete hooray; }
private: menu *menu_de, *menu_en, *menu3; echo *hurra, *hooray; };
int main() { main_menu m; m(); }
|
-- Einfachheit ist Voraussetzung für Zuverlässigkeit. -- Edsger Wybe Dijkstra Dieser Post wurde am 15.03.2005 um 21:27 Uhr von 0xdeadbeef editiert. |