如何使用ifstream对象的shared_ptr指针插入运算符?

时间:2013-07-20 07:19:15

标签: c++ c++11 shared-ptr ifstream

我正在尝试使用shared_ptr指针从文件中读取。我不知道如何使用插入操作符。这是代码:

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

int main()
{
    string path="";    
    map<string, int> container;
    cout<<"Please Enter Your Files Path: ";
    getline(cin,path);

    shared_ptr<ifstream> file = make_shared<ifstream>();
    file->open(path,ifstream::in);
    string s="";
    while (file->good())
    {
        file>>s;
        container[s]++;
        s.clear();
    }

    cout <<"\nDone..."<< endl;
    return 0;
}

简单地做:

file>>s;

不起作用。

如何获取文件指向的当前值(我不想得到整行,我只需要以这种方式获取它们出现的单词和数量)。

顺便说一下,我使用shared_ptr来避免自己关闭文件,做一个这种类型的指针,shared_ptr(smart)是否足以不自己编写file->close()?或者他们无关紧要?

2 个答案:

答案 0 :(得分:4)

最简单的方法是使用取消引用operator *

(*file) >> s;

但是看看代码,我认为没有理由使用智能指针。您可以使用ifstream对象。

std::ifstream file(path); // opens file in input mode

答案 1 :(得分:3)

为什么你想让它成为指针?这就是让你痛苦的原因。

ifstream file;
file.open( ...
...
file>>s;

Streams旨在被视为值(而不是指针类型)。在ifstream上调用析构函数时,文件将被关闭。

如果需要将流对象传递给代码的其他部分,只需使用引用(对基类):

void other_fn( istream & f )
{
    string something;
    f>>something;
}

ifstream file;
other_fn( file );

因为f参数是引用,所以当它超出范围时,它不会尝试关闭流/文件 - 这仍然发生在定义原始ifstream对象的范围内。