Search code examples
c++file-read

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

Solution

  • 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