This is my solution to OOP344's "basicMath" problem. User is suppose to call the program from
command line with a simple mathematical expression (i.e bm a + b).
**Fixed some errors regarding validation**
/*
Program: basicMath.cpp
Date: September 25, 2013
Author: Benson Wong
Purpose: To practice coding for command line arguments
*/
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
bool NaN(char* x);
int main(int argc, char** argv)
{
double a;
double b;
a = b = 0;
bool error = false;
if (argc == 4) {
if (NaN(argv[1]) || NaN(argv[3])) {
error = true;
} else {
a = atof(argv[1]);
b = atof(argv[3]);
if (!strcmp(argv[2], "+")) {
cout << a << " + " << b << " = " << a + b << endl;
} else if (!strcmp(argv[2], "-")) {
cout << a << " - " << b << " = " << a - b << endl;
} else if (!strcmp(argv[2], "x")) {
cout << a << " x " << b << " = " << a * b << endl;
} else if (!strcmp(argv[2], "/") && argv[3] != 0) {
cout << a << " / " << b << " = " << a / b << endl;
} else
error = true;
}
} else
error = true;
if (error) {
cout << "bm <number> <+-x/> <number><ENTER>" << endl;
}
return 0;
}
bool NaN(char *x)
{
int i;
int d;
bool ec = false;
i = d = 0;
if (x[0] == '-') {
i++;
}
for (; x[i] != '\0' && ec == false; i++) {
if (x[i] == '.') {
d++;
if (d > 1) {
ec = true;
}
} else if (!isdigit(x[i])) {
ec = true;
}
}
return ec;
}
Sunday, 22 September 2013
OOP344's Basic Math
Subscribe to:
Posts (Atom)