Liebe Leserinnen, liebe Leser,

als es im Vorwort dieser Webseite geäußert ist, habe ich mich mit Programmierung, insbensondere C++ Programmierung, zu beschäftigen begonnen. Die erste von mir gemachte Sache war die Durchsuchung der C++ Syntax auf cplusplus.com, die für weitere Befragungen auch eine gute Webseite ist. Das reicht natürlich nicht, um alle Fähigkeiten der Sprache zu begreifen, dennoch ist es eine Stelle, wo man starten kann. Nachdem ich einen Übersicht über die Programmierungssprache auf dieser Webseite bekommen habe, habe ich sie zu einem Buch (von Bjarne Stroustrup) getauscht, das tatsächlich für Anfänger geschrieben ist. Nachdem ich ein paar Kapitel gelesen habe, konnte ich schon den unten zu sehende Code schreiben. Das ist nicht viel, aber nach dem klassischen “Hello World” Programm ist es etwas, das etwas Nutzbares machen kann:
C++
// my very first program, a simple calculator
#include <iostream>
using namespace std;
int main() {
char operation;
double operand1, operand2, result;
bool good_operation = false;
cout << "Specify operation (+,-,*,/) and operands in the following format: 1+1\n";
cin >> operand1 >> operation >> operand2;
// This is too 'if'y. Use 'switch' instead. Also, it is harder to handle
// erroneous operations with this approach.
// if (operation == '+') {result = operand1+operand2;}
// if (operation == '-') {result = operand1-operand2;}
// if (operation == '*') {result = operand1*operand2;}
// if (operation == '/') {result = operand1/operand2;}
// cout << "Result of " << operand1 << operation << operand2 << " is " << result << "\n";
while (good_operation==false) {
switch (operation) {
case'+':
result = operand1+operand2;
cout << "Result of " << operand1 << operation
<< operand2 << " is " << result << "\n";
good_operation = true; // lack of this results in infinite loop
break; // lack of this results in executing next case too
case'-':
result = operand1-operand2;
cout << "Result of " << operand1 << operation
<< operand2 << " is " << result << "\n";
good_operation = true;
break;
case'*':
result = operand1*operand2;
cout << "Result of " << operand1 << operation
<< operand2 << " is " << result << "\n";
good_operation = true;
break;
case'/':
result = operand1/operand2;
cout << "Result of " << operand1 << operation
<< operand2 << " is " << result << "\n";
good_operation = true;
break;
default:
cout << "Unrecognized operation. Please enter a correct one (+,-,*,/):\n";
cin >> operation;
}
}
return 0;
}