I found the tutorial useful to get started but not very robust. I/O (cin) can be little tricky to deal with
so I'm releasing this for the c++ newbies to help them ramp up quicker.
CalcTutorial.cpp
//////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
////
//// Author: Adam Danischewski, Created Date: 20190812, Version: v1.0
//// Derivative Work - Released under Creative Commons License CC BY-SA 4.0
//// Orig. Source: https://tutorials.visualstudio.com/cpp-calculator/intro
////
///////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
#include <iostream>
#include "Calc.h"
#include <string>
using namespace std;
int main()
{
double x = 0.0;
double y = 0.0;
double result = 0.0;
const int BUFCLR = 10000; //Note: it will loop until the buffer "makes sense".
string myinput;
char oper = '+';
cout << "Calculator Console Application - (Type \"exit\" to quit)" << endl << endl;
cout << "Please enter the operation to perform. Format: a+b | a-b | a*b | a/b"
<< endl;
Calculator c;
while (true)
{
if (cin.fail()) {
cin.clear();
cin.ignore(BUFCLR, '\n');
}
cout << "Calc: ";
if (cin >> x >> oper >> y) {
switch (oper) {
case '/':
case '+':
case '-':
case '*':
break;
default:
cout << "Error: Invalid operator (" << oper << "), operator must be in [+-*/]." << endl;
continue;
}
if (oper == '/' && y == 0) {
cout << "Error: Division by 0 exception, RHS must be > 0." << endl;
continue;
}
result = c.Calculate(x, oper, y);
cout << "Result is: " << result << endl;
}
else {
cin.clear(); // Clear cin fail state.
getline(cin, myinput);
if (myinput == "exit") {
cout << "Thanks for using Calc, bye.." << endl;
exit(0);
}
else {
myinput = "Error: Bad input (" + myinput + "), Format: a+b | a-b | a*b | a/b";
cout << myinput << endl;
}
}
}
return 0;
}
Calc.h
#pragma once
class Calculator
{
public:
double Calculate(double x, char oper, double y);
};
Calc.cpp
#include "Calc.h"
double Calculator::Calculate(double x, char oper, double y)
{
switch (oper)
{
case '+':
return x + y;
case '-':
return x - y;
case '*':
return x * y;
case '/':
return x / y;
default:
return 0.0;
}
}
No comments:
Post a Comment