How do I input equations
3+2-43+5
Equations can be any size
it can have 200 numbers (Size is unlisted)
No idea, I have another program using strings to store the question
This is what I tried.
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
|
#include <iostream>
using namespace std;
int main()
{
int number, senumb, sum = 0;
char kind;
cout << "Enter an expression: ";
while(cin >> number >> kind >> senumb) //very redundant
{
if(sum == 0)
{
sum = number;
}
if(kind == '+')
{
sum = sum + senumb;
}
if(kind == '-')
{
sum = sum - senumb;
}
}
cout << kind << endl;
cout << sum << endl;
system("pause");
return 0;
}
|
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
|
#include <iostream>
#include <string>
using namespace std;
int main()
{
string expression = "";
cout << "Enter your math equation, insert a semicolon after your equation: ";
getline(cin,expression);
//remove spaces
for(int i = 0;i < expression.length();i++)
{
if(expression[i] == ' ')
{
expression.erase(expression.begin() + i);
i--;
}
}
int leftnumber = 0, rightnumber = 0;
string proxyline = "";
int beg = 0,end;
for(int i = 0;i < expression.length();i++)
{
if(expression[i] == '+')
{
end = i;
for(beg;beg < end;beg++)
{
proxyline += expression[beg];
}
leftnumber += atoi(proxyline.c_str());
proxyline.clear();
beg = i+1;
}
if(expression[i] == '-')
{
end = i;
for(beg;beg < end;beg++)
{
proxyline += expression[beg];
}
leftnumber -= atoi(proxyline.c_str());
proxyline.clear();
beg = i+1;
}
}
for(int i = end; end < expression.length();end++)
{
if(expression[end] == '+')
{
for(int j = end + 1;j < expression.length();j++)
{
proxyline += expression[j];
}
leftnumber += atoi(proxyline.c_str());
proxyline.clear();
}
if(expression[end] == '-')
{
for(int k = end + 1;k < expression.length();k++)
{
proxyline += expression[k];
}
leftnumber += atoi(proxyline.c_str());
proxyline.clear();
}
}
cout << "The answer is: " << leftnumber << endl;
system("pause");
return 0;
}
|
Last edited on
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
#include <iostream>
#include <sstream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string expression;
cout << "Enter expression: ";
getline( cin, expression );
expression.erase( remove( expression.begin(), expression.end(), ' ' ), expression.end() );
stringstream ss( expression );
int result = 0, num;
while( ss >> num ) result += num;
cout << expression << " = " << result << '\n';
}
|
Enter expression: 3 +2 - 43 + 5
3+2-43+5 = -33 |
Last edited on
Topic archived. No new replies allowed.