0

I am learning C++ simple input and output some text, however it seems to be in a dead loop for some reasons, any advise is much appreciated.

#include <iostream>
#include <string>
#include <fstream>
#include <memory>
using namespace std;

int main(int argc, const char * argv[])
{
    std::shared_ptr<std::string> fileName(new std::string);
    bool validFileName = false;
    bool quit = false;
    while (!quit)
    {
        while (!validFileName)
        {
            std::cout << "Please enter text file to out print ots content" << std::endl;
            std::cin >> (*fileName);
            validFileName = !(fileName->find(".txt") == std::string::npos);
            quit = fileName->compare("q") == 0;
            if (quit)
            {
                continue;
            }
        }

        std::shared_ptr<std::ifstream> reader(new std::ifstream);
        reader->open(*fileName);
        if (reader->is_open()){
            while (!reader->eof()){
                std::shared_ptr<std::string> line(new std::string);
                getline(*reader, *line);
                std::cout << *line << std::endl;
            }
            reader->close();
        }
        else {
            throw std::exception();
        }

    }
    std::cout << "Bye" << std::endl;
}
Mat
  • 188,820
  • 38
  • 367
  • 383
  • Check out: http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – Mat May 14 '14 at 14:11
  • A bit off the question, but you should use automatic variables whenever possible, instead of that java-ish thing of doing everything with new. That is, write `std::string fileName;` instead of `std::shared_ptr filename(new std::string)`, and so on. – rodrigo May 14 '14 at 14:32
  • lol, I like that. `If quit, then continue` – Steve H May 14 '14 at 15:28

0 Answers0