反向字问题 - 程序卡在输入循环中?

时间:2011-05-05 07:41:32

标签: c++ file-read

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

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

5 个答案:

答案 0 :(得分: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;
}

斯利拉姆

答案 1 :(得分: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(?)
}

答案 2 :(得分:0)

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

答案 3 :(得分:0)

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

答案 4 :(得分: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。