[英]C++ unable check ifstream/ofstream.is_open() inside a function
我已經用C ++編寫了一個代碼,該代碼從文本文件讀取或使用ifstream
/ ofstream
創建新代碼。 我想使用fstream
.is_open
成員函數添加檢查,以查看文件是否成功打開。 它在主循環內可以正常工作。 然后,我為此嘗試在循環外創建一個函數,並在main
內調用它,然后出現以下錯誤:
std::ios_base::ios_base(const std::ios_base&)
是私有的。
是否可以在主循環之外進行檢查? 怎么樣? 我究竟做錯了什么?
如果您能提供幫助,我將不勝感激。 您可以在下面找到代碼。
PS我是C ++的新手,因此,如果有的話,請不要批評非專業的編程方法。 盡管任何改進建議都值得歡迎。
#include <iostream>
#include <fstream>
using namespace std;
void check_opened(ifstream toget, ofstream togive){
if(toget.is_open()){
cout<<"able to open file(toread.txt)"<<endl;
}
else {
cout<<"failure"<<endl;
}
if(togive.is_open()){
cout<<"able to create/open a file(newone.txt)"<<endl;
}
else {
cout<<"failure"<<endl;
}
}
int main () {
ifstream toget;
ofstream togive;
toget.open("toread.txt");
togive.open("newone.txt");
check_opened(toget,togive);
toget.close();
togive.close();
return 0;
}
函數check_opened
不引用流,而是引用一個流的副本。 因此,當您調用check_opened時,您的主函數會隱式調用ifstream
和ofstream
的副本構造函數,它們是私有的,這會導致錯誤。 將check_opened的簽名更改為void check_opened(ifstream&, ofstream&)
將解決您的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.