我正在解决ArithmaticII。我得到以下输入的正确输出:
4 1 + 1 * 2 = 29 / 5 = 103 * 103 * 5 = 50 * 40 * 250 + 791 =
输出:
4 5 53045 500791
我得到了正确的输出,但是当我将解决方案提交给spoj时,我得到了SIGABRT
运行时错误。
注意:它还可能包含空格以提高可读性。
由于输入可能不包含空格,我该如何处理,因为这给了我错误。
因为当我没有在输入中提供空间时我的程序停止(运行时错误)(1 * 1 + 2 =)
terminate called after throwing an instance of 'std::invalid_argument' what(): stoll
请帮忙。我该怎么办?
#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);
}
}
}
}
一次输入一行。将第一个数字放入ans。然后按字符循环遍历字符串chararcter的其余部分。如果字符是算术运算符('*'或'+'或'/'或' - '),则在它之后会有一个数字。提取数字并执行指定的操作。如果字符是'='则打印答案。
提示:如何提取数字?
1.第一个数字从开始开始直到第一个算术运算符。 2.所有其他数字都在算术运算符之间或'='。