c++ - 我很难打印换行符

标签 c++

我是解决问题的新手。我正在解决 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;
}

最佳答案

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

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;

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

关于c++ - 我很难打印换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12571867/

相关文章:

c++ - opengl渲染半个圆柱体

c++ - C++ ABI如何处理RVO和NRVO?

c++ - cin:检查数字是整数还是 float ,即使浮点值是 1.000

c++ - 为什么关系运算符在 STL 字符串中重载为非成员函数?

c++ - openCV 中用于颜色识别的 HSV 图像

c++ - 二分法搜索的终点

c++ - C/C++ 内存问题?

c++ - 作为非类型模板参数的常量字符串引用

C++ 定义由一组固定整数组成的类型的最佳方法

c++ - NSIS:ExecWait 如何处理否则会崩溃的 exe