1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
|
#include <iostream>
#include <cctype>
using std::cout;
using std::endl;
using std::cin;
void eatspaces(char* str);
double addNumbers(char* str);
double number(char* str, int& index);
double decimal(char* str, int& index);
int main(void)
{
char str[15];
cout << "Calculator: " << endl
<< "+ - add" << endl
<< "- - substract" << endl
<< "* - multiply" << endl
<< "/ - divide" << endl << endl;
char cont = 'y';
//continue solving equations until they say to stop
while (cont == 'y' || cont == 'Y')
{
cin.getline(str, 15, '\n');
eatspaces(str);
double sum = addNumbers(str);
cout << "\t = " << sum << endl;
cout << "Continue(Y/N)? ";
cin >> cont;
cin.ignore(1, '\n');
}
return 0;
}
void eatspaces(char* str)
{
//remove all spaces from the string entered
int i = 0;
int j = 0;
while((*(str + i) = *(str + j++)) != '\0')
if (*(str + i) != ' ')
i++;
return;
}
double number(char* str, int& index)
{
//get the value of the next number in the series and increment index to the next position
double number = 0;
while(isdigit(*(str + index)))
{
number *= 10;
number += (*(str + index)) - '0';
index++;
}
//if no decimal return the number
if(*(str + index) != '.')
return number;
//if there is a decimal add it to the number and then return it
else
index++;
return (number + decimal(str, index));
}
double decimal(char* str, int& index)
{
//get the value of a decimal after the number if there is one
double decimal = 0;
double multiplier = .1;
while(isdigit(*(str + index)))
{
decimal += (*(str + index) - '0') * multiplier;
multiplier /= 10;
index++;
}
return decimal;
}
double addNumbers(char* str)
{
int index = 0;
double total = 0;
//get the value of the first term
total += number(str, index);
for(;;)
{
switch(*(str + index))
{
//run through each operaton and perform the needed operation to the total value
case '+':
index++;
total += number(str, index);
break;
case '-':
index++;
total -= number(str, index);
break;
case '*':
index++;
total *= number(str, index);
break;
case '/':
index++;
total /= number(str, index);
break;
case '\0':
//if at the end of the string return the total value
return total;
default:
//if invalid input, show where the error occured and close the program
cout << endl << endl;
cout << "ERROR AT POSITION " << index << endl;
cout << str << endl;
for (; index > 0; index--)
cout << " ";
cout << "^";
cout << endl;
exit(1);
}
}
return total;
}
|