簡體   English   中英

如何將插入運算符與ifstream對象的shared_ptr指針一起使用?

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

我正在嘗試使用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()嗎? 還是不相關?

最簡單的方法是使用解引用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對象的范圍中仍然會發生這種情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM