首页 > 解决方案 > 如何在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);
            }
        }
    }
}

标签: c++stringstream

解决方案


一次输入一行。将第一个数字放入ans。然后逐个字符循环遍历字符串的其余部分。如果字符是算术运算符('*' or '+' or '/' or '-')那么后面会有一个数字。提取数字并执行指定的操作。如果字符是 '=' 打印答案。

提示:如何提取数字?

1.第一个数字从头开始直到第一个算术运算符。
2. 所有其他数字都在算术运算符或“=”之间。


推荐阅读