1

我正在尝试解决反向单词问题。我的解决方案有效,甚至跳过了空白行。但是,在读取文件的所有行之后,程序会陷入循环,不断地接受输入。这很令人费解,我觉得这与我的外部 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;
}
4

5 回答 5

1

问题是内部循环。如果我在一个单行上只包含一个单词的文本文件,它将失败,因为它永远不会退出内部循环。

这段代码对我有用:

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;
}

斯里拉姆

于 2011-05-05T07:46:21.277 回答
1

这是一种可能有效的方法。

// read the file line by line
string line;
while (std::getline(in, line))
{
  if (!line.empty())
  {
    // now have a valid line, extract all the words from it
    <input string stream> in_str(line); // construct a input string stream with the string
    string word;
    while (in_str >> word)
    {
      // push into the stack
    }
    // now print the contets of the stack
  }
  else
    // print a blank line(?)
}
于 2011-05-05T07:58:49.990 回答
0

最后一个条件应该是while(in).

于 2011-05-05T07:45:06.673 回答
0

尝试使用while(in >> t) {...}

于 2011-05-05T07:46:27.650 回答
0

这:

while(in.peek() != -1 || in.fail() || in.eof() || in.bad() );

肯定应该是:

while(in.peek() != -1 && (! in.fail()) && (!  in.eof()) && (! in.bad()) );

或者,更好的是,只需测试流:

while( in && in.peek != -1 )

我认为-1实际上应该是EOF。

于 2011-05-05T07:47:53.850 回答