20分求助,使用stringstream转化类型

P1957 口算练习题

czcyf @ 2022-04-22 11:28:07

样例过了,但只有20分……

怀疑是数长度的时候出了问题……

#include <bits/stdc++.h>
using namespace std;

int main()
{
    int n;
    cin >> n;
    scanf("\n");
    char op;
    for (int i=1;i<=n;i++)
    {
        string s;
        getline(cin,s);
        int st=0,a,b,c,flag;
        if (isalpha(s[0])) op=s[0],st=2;
        for (int j=st;j<=s.length();j++)
            if (isspace(s[j])) flag=j;
        string s1=s.substr(st,flag-st),s2=s.substr(flag+1,s.length()-flag),s3;
        stringstream ss;
        ss<<s1;ss>>a;ss.clear();
        ss<<s2;ss>>b;ss.clear();
        //cout << s1 << " " << s2 << endl;
        //到这儿貌似还没问题
        stringstream tmp;
        if (op=='a')
        {
            c=a+b;
            tmp<<c;tmp>>s3;
            cout << a << '+' << b << '=' << c << endl;
            cout << s1.length()+s2.length()+s3.length()+1 << endl;
        }
        else if (op=='b')
        {
            c=a-b;
            tmp<<c;tmp>>s3;
            cout << a << '-' << b << '=' << c << endl;
            int len=s1.length()+s2.length()+s3.length()+1;
            if (c<0) len++;
            cout << len << endl;
        }
        else if (op=='c')
        {
            c=a*b;
            tmp<<c;tmp>>s3;
            cout << a << '*' << b << '=' << c << endl;
            cout << s1.length()+s2.length()+s3.length()+1 << endl;
        }
    }
    return 0;
}

求大佬指教,谢谢!


|