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
|
#include<iostream>
#include<cstring>
using std::cout;
using std::cin;
using std::endl;
int findSign(char expression[], int length);
char* removeSpace(char* string, int length, char* spaceless, int& spaceCounter);
int add(char equation[], int loc, int length);
int main(void)
{
//get equation from user
const int max = 50;
char entered[max];
cin.getline(entered, 50, '\n');
int len = strlen(entered);
char* expression = new char[len];
int length = sizeof expression/sizeof expression[0];
//get rid of all spaces
int spaceCounter = 0;
char* equation = new char[length];
equation = removeSpace(expression, length, equation, spaceCounter);
//find the + sign and the total
int loc = findSign(equation, length);
int total = add(equation, loc, length);
cout << total;
//clear memory and close the program
delete[] expression;
delete[] equation;
expression = 0;
equation = 0;
cout << endl;
return 0;
}
char* removeSpace(char* string, int length, char* spaceless, int& spaceCounter)
{
//remove all the spaces by adding all characters that arent spaces to the spaceless array
for (int i = 0; i < length; i++)
{
if (string[i] == ' ')
continue;
else
{
spaceless[spaceCounter] = string[i];
spaceCounter++;
}
}
return spaceless;
}
int findSign(char expression[], int length)
{
//locate the + sign
int location = 0;
for (int i = 0; i < length; i++)
{
if (expression[i] == '+')
{
location = i;
}
}
return location;
}
int add(char equation[], int loc, int length)
{
//add the two numbers
int num1 = 0, num2 = 0;
int i = 0;
for (; i < loc; i++)
{
num1 += (equation[i] - 48); //subtract 48 to convert from ascii to a decimal
cout << equation[i] << endl;
}
for (; i < length - 1; i++)
{
num2 += (equation[i] - 48); //subtract 48 to convert from ascii to a decimal
cout << equation[i] << endl;
}
return num1 + num2;
}
|