Anfänger-Taschenrechner mal richtig gemacht
-
Was haltet ihr von dieser Implementation des "Taschenrechners" wie ihn jeder Anfänger mal schreibt:
#include <iostream> #include <functional> #include <limits> #include <map> #include <boost/function.hpp> int main() { using std::cout; using std::cin; using std::endl; typedef boost::function< double( double, double ) > arithmetic_func; typedef std::map< char, arithmetic_func > operation_table; operation_table operations; operations.insert( make_pair( '+', std::plus< double >() ) ); operations.insert( make_pair( '-', std::minus< double >() ) ); operations.insert( make_pair( '*', std::multiplies< double >() ) ); operations.insert( make_pair( '/', std::divides< double >() ) ); char op; double arg1, arg2; while( !( ( cout << "Enter the arithmetic operations in the following syntax: " "[op] [arg1] [arg2]\nExpression: " ) && ( cin >> op && cin >> arg1 && cin >> arg2 ) ) ) { cout << "\nInvalid expression. Try again." << endl; cin.clear(); cin.ignore( std::numeric_limits< std::streamsize >::max(), '\n' ); } operation_table::const_iterator it = operations.find( op ); if( it == operations.end() ) { cout << "\nUnsupported operation: " << op << endl; } cout << ( it->second )( arg1, arg2 ); }
-
nichts, da ein anfänger mit so einem beispiel nichts anfangen kann.
-
Hmm vllt wäre es auch sinnvoll die Konsole offen zu halten -.-
-
C++-Lehrmeister schrieb:
Was haltet ihr von dieser Implementation des "Taschenrechners"...
da sieht man mal, wie pervers sowas aussehen kann

was ist denn diese 'operation_table' ?
-
Hallo
was ist denn diese 'operation_table' ?
Steht eine Zeile über der ersten Benutzung :
Ein typedef auf eine Map von chars (den Operationssymbolen) auf Funktoren (die Operation)bis bald
akari
-
akari schrieb:
Hallo
was ist denn diese 'operation_table' ?
Steht eine Zeile über der ersten Benutzung :
Ein typedef auf eine Map von chars (den Operationssymbolen) auf Funktoren (die Operation)danke. von dem code kriegt man augenkrebs. ich hab's voll übersehen...
:xmas2:
-
Das einzig "unschöne" ist die Bedingung in der While-Schleife die ist nicht ganz so übersichtlich aufgrund der Größe, aber von der Idee her ist es das einfachste eine Ausgabe die zur Eingabe auffordert zusammengekoppelt in eine while-Schleife zu packen.
Hätte man in eine Funktion auslagern können, dann wäre es leserlicher geworden.