如何将插入运算符与ifstream对象的shared_ptr指针一起使用

How to use insertion operator with a shared_ptr pointer of an ifstream object?

本文关键字:ptr shared 指针 一起 对象 插入 运算符 ifstream      更新时间:2023-10-16

我正在尝试使用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(智能),不自己编写file->close()就足够了吗?或者它们无关紧要?

最简单的方法是使用解引用operator *:

(*file) >> s;

但从代码来看,我看不出有任何理由使用智能指针。您可以只使用一个ifstream对象。

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

为什么希望它是指针?正是它给你带来了痛苦。

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

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

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

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

因为f参数是一个引用,所以当流/文件超出作用域时,它不会尝试关闭它——这种情况仍然发生在定义原始ifstream对象的作用域中。