I was solving ArithmaticII. I am getting the correct output for the below input:
4 1 + 1 * 2 = 29 / 5 = 103 * 103 * 5 = 50 * 40 * 250 + 791 =
Output:
4 5 53045 500791
I am getting the correct output, but when I submit my solution to spoj, I
get a SIGABRT
runtime error.
Note: It may also contain spaces to improve readability.
Since the input might not contain spaces, how can I handle that, because that is giving me error.
because my program stops (runtime error) when I don't provide space in the input (1 * 1+2=)
terminate called after throwing an instance of 'std::invalid_argument' what(): stoll
Please help. What should I do?
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
int main() {
int t;
string str;
cin >> t;
while (t--) {
///using cin.ignore() as input as preceded by a single line
cin.ignore();
getline(cin, str, '\n');
stringstream split(str);
///now use getline with specified delimeter to split string stream
string intermediate;
int flag = 0;
long long int ans=1;
while (getline(split, intermediate, ' ')) {
if (intermediate == "=") {
cout << ans<<"\n";
break;
}
if (intermediate == "*") {
flag = 1;
continue;
}
else if (intermediate == "/") {
flag = 2;
continue;
}
else if (intermediate == "+") {
flag = 3;
continue;
}
else if(intermediate == "-"){
flag = 4;
continue;
}
if (flag == 1) {
ans *= stoll(intermediate);
}
else if (flag == 2) {
ans /= stoll(intermediate);
}
else if (flag == 3) {
ans += stoll(intermediate);
}
else if (flag == 4) {
ans -= stoll(intermediate);
}
else if (flag == 0) {
ans = stoll(intermediate);
}
}
}
}