我正在尝试解决反词问题。我的解决方案有效,甚至跳过空白行。但是,在读取了文件的所有行之后,程序陷入了循环,不断接受输入。这非常令人困惑,我觉得这与我的外部while循环有关,但是我看不出它到底出了什么问题。

#include <iostream>
#include <fstream>
#include <string>
#include <stack>

using namespace std;

int main(int argc, char** argv)
{
    stack<string> s;
    ifstream in;
    in.open(argv[1]);
    do
    {
        do
        {
            string t;
            in >> t;
            s.push(t);
        } while(in.peek() != '\n');
        do
        {
            cout << s.top();
            s.pop();
            if(s.size() > 0) cout << " ";
            else cout << endl;
        } while(s.size() > 0);
    } while(in.peek() != -1 || in.fail() || in.eof() || in.bad() );
    in.close();
    return 0;
}

最佳答案

问题是内部循环。如果我在一行中只输入一个单词的文本文件,它将失败,因为它永远不会出现在内部循环之外。

该代码对我有用:

int main(int argc, char** argv)
{
    stack<string> s;
    ifstream in;
    in.open(argv[1]);
    do
    {
        do
        {
            string t;
            in >> t;
            s.push(t);
        } while((in.peek() != '\n') && (in.peek() != -1));
        do
        {
            cout << s.top();
            s.pop();
            if(s.size() > 0) cout << " ";
            else cout << endl;
        } while(s.size() > 0);
    } while(in.peek() != -1 && !(in.fail()) && !(in.eof()) && !(in.bad()) );
    in.close();
    return 0;
}

斯里拉姆

10-05 21:04
查看更多