calculator

Feb 27, 2018 at 3:13am
I want to make a simple calculator that can add and subtract integers, and will accept arbitrarily long mathematical formulas composed of symbols +, -, and non-negative integer numbers.

Imagine you have a file formula.txt with the summation formula such as:

100 + 50 - 25 + 0 + 123 - 1

If you redirect the file into your program, it should compute and print the answer:

$ ./calc < formula.txt
247

Specifically, write a program calc.cpp that reads from the cin a sequence of one or more non-negative integers written to be added or subtracted. Space characters can be anywhere in the input. After the input ends (end-of-file is reached), the program should compute and print the result of the input summation.
Last edited on Feb 27, 2018 at 10:30pm
Feb 27, 2018 at 10:36am
You cannot use the actual sign for the calculation because it will be applied to the following number.

I suggest that you create another variable like char last_sign = 0;. Line 9/12 uses last_sign. After the calculation is done set last_sign to sign at the bottom of the loop.

Notice that after the loop is done you need to make a final calculation.
Feb 27, 2018 at 5:08pm
Thank you for your suggestions. But I figure it out by myself!
I just need to read cin twice.
Thanks though!
Last edited on Feb 27, 2018 at 10:31pm
Feb 27, 2018 at 5:21pm
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
#include <iostream>
#include <sstream>
#include <string>
#include <cctype>
using namespace std;

string noBlanks( string str )
{
   string result;
   for ( char c : str ) if ( !isspace( c ) )  result += c;
   return result;
}

int main()
{
   int num;
   int sum = 0;
   string line;

   cout << "Input an expression: ";
   getline( cin, line );
   line = noBlanks( line );
   stringstream ss( line );
   while ( ss >> num ) sum += num;

   cout << "Result is " << sum << '\n';
}

Input an expression: 100 + 50 - 25 + 0 + 123 - 1
Result is 247
Topic archived. No new replies allowed.