c++ - 如何在cpp中处理stringstream中的空格?
问题描述
我正在解决ArithmaticII。我得到以下输入的正确输出:
4 1 + 1 * 2 = 29 / 5 = 103 * 103 * 5 = 50 * 40 * 250 + 791 =
输出:
4 5 53045 500791
我得到了正确的输出,但是当我将我的解决方案提交给 spoj 时,我得到了一个SIGABRT
运行时错误。
注意:它还可能包含空格以提高可读性。
由于输入可能不包含空格,我该如何处理,因为这给了我错误。
因为当我没有在输入中提供空间时我的程序停止(运行时错误)(1 * 1+2=)
在抛出 'std::invalid_argument' 的实例后调用终止 什么():斯托尔
请帮忙。我应该怎么办?
#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。然后逐个字符循环遍历字符串的其余部分。如果字符是算术运算符('*' or '+' or '/' or '-')那么后面会有一个数字。提取数字并执行指定的操作。如果字符是 '=' 打印答案。
提示:如何提取数字?
1.第一个数字从头开始直到第一个算术运算符。
2. 所有其他数字都在算术运算符或“=”之间。
推荐阅读
- php - 将数组排序为升序
- python - 不同场景的随机浮点数
- spring-webflux - 如何在 Spring Webflux / RSocket 中负载平衡通道
- r - 如何将不整洁的列表翻译成整洁的数据框?
- selenium - 使用 Selenium WebDriver 清除浏览器缓存和历史记录
- node.js - 如果用户登录,想要重定向用户
- python - Jinja2 中的上下文是什么?
- azure-cognitive-search - 技能输出映射到 Edm.DateTimeOffset 字段
- splunk - 如何在 splunk 中配置 eml 数据格式
- stm32 - 如何将 RF96W 与基于 Stm32F030 的控制器连接?