簡體   English   中英

C ++無法檢查函數內部的ifstream / ofstream.is_open()

[英]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時,您的主函數會隱式調用ifstreamofstream的副本構造函數,它們是私有的,這會導致錯誤。 將check_opened的簽名更改為void check_opened(ifstream&, ofstream&)將解決您的問題。

暫無
暫無

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

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