我在打印换行符时遇到困难

问题描述 投票:0回答:1

我是解决问题的新手。我当时正在解决 UVA 中一个名为“表达”的问题。我认为我已经解决了问题,因为我的代码为每个可能的测试用例提供了正确的输出。但我仍然得到了 WA。

似乎在某个地方我打印了一个换行符,但我做得不正确。问题说:

输出文件会将每个后缀表达式全部放在一行上。在不同表达式之间打印一个空行。

我已经在群里提出了这个问题,但没有得到答案。之前的讨论也没有帮助。接下来我可以尝试什么?

#include<iostream>
#include<map>
#include<stack>
#include<vector>
#include<cstdio>

using namespace std;

void push_into_stack(char c, vector< char > &ans, stack< char > &st);
void work_with_stack(vector< char > &ans, stack< char > &st);

int main(void)
{
    freopen("input.txt", "r", stdin);
    int t;
    char dummy;
    cin >> t;
    
    for(int i=1; i<=t; i++)
    {
        vector< char > exp, ans;
        stack< char > st;
        char c;
    
        while(cin >> c)
            exp.push_back(c);
    
        for(int i=0; i<exp.size(); i++)
            if(exp[i]=='+' || exp[i]=='-' || exp[i]=='*' || exp[i]=='/') push_into_stack(exp[i], ans, st);
            else if(exp[i]=='(') st.push(exp[i]);
            else if(exp[i]==')') work_with_stack(ans, st);
            else ans.push_back(exp[i]);
    
        while(!st.empty())
        {
            ans.push_back(st.top());
            st.pop();
        }
    
        for(int i=0; i<ans.size(); i++)
            cout << ans[i];
        cout << endl;
    }
    return 0;
}

void push_into_stack(char c, vector< char > &ans, stack< char > &st)
{
    map< char, int > mp;
    mp['/']=2;
    mp['*']=2;
    mp['+']=1;
    mp['-']=1;

    while(true)
    {
        if(!st.empty() && mp[c]<=mp[st.top()])
        {
            ans.push_back(st.top());
            st.pop();
        }
        else
        {
            st.push(c);
            break;
        }
    }
    return;
}

void work_with_stack(vector< char > &ans, stack< char > &st)
{
    while(true)
    {
        if(st.top()=='(') break;
        ans.push_back(st.top());
        st.pop();
    }
    st.pop();
    return;
}
c++
1个回答
1
投票

嗯...我想答案的质量只能反映问题的质量...但是怎么样:

int main(void) {
   char postfixone[] = "4 5 7 2 + - *            -16";
   char postfixtwo[] = "3 4 + 2  * 7 /             2";
   char postfixthree[] = "5 7 + 6 2 -  *            48";
   printf("%s\n\n",postfixone);
   printf("%s\n\n",postfixtwo);
   printf("%s\n\n",postfixthree);
}

mike@linux-4puc:~> ./a.out 
4 5 7 2 + - *            -16

3 4 + 2  * 7 /             2

5 7 + 6 2 -  *            48

每个都在一行上,中间有一个新行...

编辑: 我猜你正在使用 C++ 并在此处打印这些行:

for(int i=0; i<ans.size(); i++)
     cout << ans[i];
 cout << endl; 

您正在使用 endl 为每个后缀打印一个新行,请尝试:

 cout << endl << endl;

而是在行之间插入额外的空白。

© www.soinside.com 2019 - 2024. All rights reserved.