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

問題は内側のループです。1 行に 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.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 に答える
0

最後の条件はwhile(in).

于 2011-05-05T07:45:06.673 に答える
0

使ってみてwhile(in >> t) {...}

于 2011-05-05T07:46:27.650 に答える