Reverse word problem - program stuck in input loop?
I am trying to solve the reverse word problem. My solution works, and even skips blank lines. However, after all the lines of a file are read, the program gets stuck in a loop, constantly accepting input. This is very puzzling, and I feel like it has to do wit开发者_开发百科h my outer while loop, but I can't see what's wrong with it.
#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;
}
The problem is the inner loop. If I give in a text file containing only one word on a single line, it will fail since it will never come out of the inner loop.
This code works for me:
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;
}
Sriram
Here is an approach that may work.
// 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(?)
}
The last condition should just be while(in)
.
Try using while(in >> t) {...}
This:
while(in.peek() != -1 || in.fail() || in.eof() || in.bad() );
should surely be:
while(in.peek() != -1 && (! in.fail()) && (! in.eof()) && (! in.bad()) );
Alternatively, and better, just test the stream:
while( in && in.peek != -1 )
And I think that -1 should actually be EOF.
精彩评论