![](/img/trans.png)
[英]How to wrap a raw pointer into a shared_ptr and prevent shared_ptr from deleting the object?
[英]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.