Addition Calculator (tweaked)

I wrote some code for an addition calculator. It adds more than 2 numbers at a time.

The way to input the numbers is: num1+num2+num3...

Example output:


Addition expression (num1+num2+num3...):
12+45+23+1+1+3
Answer: 85




Is there any better way to do this? Than the one below.

Code:

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
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
bool isOperand(const char&);
int main()
{
	std::string expression, temp;
	long long int valTemp = 0, sum = 0;
	for (;;)
	{
		std::vector<long long int> ops = {0};
		std::cout << "Addition expression (num1+num2+num3...):\n";
		std::cin >> expression;
		for (char c : expression)
		{
			if (!isOperand(c))
			{
				temp = c;
				std::istringstream convert(temp);
				convert >> valTemp;
				*(ops.end() - 1) *= 10;
				*(ops.end() - 1) += valTemp;
			}
			else { ops.push_back(0); }
		}
		std::cout << "Answer: ";
		for (const auto &c : ops) { sum += c; }
		std::cout << sum << "\n\n";
		sum = 0;
	}
	return 0;
}
bool isOperand(const char &c)
{
	if ((c == '+') || (c == '-') || (c == '*') || (c == '/'))
	{
		return true;
	}
	else { return false; }
}
Last edited on
Can you not:
- split your string 'expression' into individual strings at the occurrences of '+'
- return this as a vector of strings
- 'stringstream' them (or use atof() or atoi()) into numbers
- add them up?

With a little care you could extend this to subtraction as well, but multiplication and division might run into precedence-of-operators issues.
@lastchance

What do you mean by "Can you not"?

Do you mean that I can't do the things you listed and I should or are you telling me not to do those things?
One suggestion would be to:
- split your string 'expression' into individual strings at the occurrences of '+'
- return this as a vector of strings
- 'stringstream' them (or use atof() or atoi()) into numbers
- add them up

With a little care you could extend this to subtraction as well, but multiplication and division might run into precedence-of-operators issues.
Last edited on
For example (and you can simplify this by removing eraseChar() if you don't need to remove any spaces in the string):
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
#include <iostream>
#include <string>
#include <vector>
using namespace std;

// Function prototypes
vector<string> split( string s, const char *delim );
string eraseChar( string s, char c );

//-------------------------------------

vector<string> split( string s, const char *delim )   // Splits a string at anything in delim
{
   vector<string> parts;
   int i = 0, idelim;

   s = eraseChar( s, ' ' );            // get rid of nuisance blanks
   while( i < s.size() && i != string::npos )    
   {
      idelim = s.find_first_of( delim, i + 1 );            // find start of NEXT item
      if ( idelim == string::npos ) parts.push_back( s.substr( i             ) );
      else                          parts.push_back( s.substr( i, idelim - i ) );
      i = idelim;
   }
   return parts;
}

//-------------------------------------

string eraseChar( string s, char c )   // Returns string without a particular character in
{ 
   int i = 0;
   string result = s;

   while( i < result.size() )
   {
      if ( result[i] == c ) result.erase( i, 1 );
      else                  i++;
   }
   return result;
}


You can then test this in full. Note that the following goes beyond your requirements because it allows minus as well as plus, as well as spaces anywhere in the expression.
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
#include <iostream>
#include <string>
#include <cstdlib>
#include <vector>
using namespace std;


// Function prototypes
vector<string> split( string s, const char *delim );
string eraseChar( string s, char c );
void display( string s );


//-------------------------------------


int main()
{
   string s;

   s = "12+45+23+1+1+3";   display( s );
   s = "1"             ;   display( s );
   s = "1"             ;   display( s );
   s = "1-3-5+20"      ;   display( s );
   s = "  1-3-5+20 "   ;   display( s );
   s = "+ 10  -  20 "  ;   display( s );
   s = "  +10  -20 "   ;   display( s );
}


//-------------------------------------


vector<string> split( string s, const char *delim )   // Splits a string at anything in delim
{
   vector<string> parts;
   int i = 0, idelim;

   s = eraseChar( s, ' ' );            // get rid of nuisance blanks
   while( i < s.size() && i != string::npos )    
   {
      idelim = s.find_first_of( delim, i + 1 );            // find start of NEXT item
      if ( idelim == string::npos ) parts.push_back( s.substr( i             ) );
      else                          parts.push_back( s.substr( i, idelim - i ) );
      i = idelim;
   }
   return parts;
}


//-------------------------------------


string eraseChar( string s, char c )   // Returns string without a particular character in
{ 
   int i = 0;
   string result = s;

   while( i < result.size() )
   {
      if ( result[i] == c ) result.erase( i, 1 );
      else                  i++;
   }
   return result;
}


//-------------------------------------


void display( string s )
{
   vector<string> parts = split( s, "+-" );
   double sum = 0;

   cout << "=====\n\nOriginal expression [" + s + "]\n";
   cout << "Parts:\n";
   for ( int i = 0; i < parts.size(); i++ ) 
   {
      cout << parts[i] + "\n";
      sum += atof( parts[i].c_str() );
   }
   cout << "Sum:\n" << sum << "\n\n";
}
Topic archived. No new replies allowed.