使用shared_ptr的C ++输入输出

时间:2014-05-14 14:03:39

标签: c++ std shared-ptr ifstream

我正在学习C ++简单输入并输出一些文本,但由于某些原因它似乎处于死循环中,任何建议都非常感激。

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

0 个答案:

没有答案