C++-将文件处理程序传递到函数中以打开时出错

C++ - Error passing file handlers into function for opening

本文关键字:出错 函数 文件 处理 程序 C++-      更新时间:2023-10-16

我有几个错误我不明白,甚至不知道如何在互联网上搜索。我尝试过"用C++函数打开文件",以及确切的错误0,但在最初的几页中没有得到太多帮助。这已经让我头疼了一段时间,甚至我的教练也帮不了我什么。尽管这是他想要的方式,不知怎么的。是的,这是家庭作业。

错误:

\driver.cpp:在函数void openFile(std::ifstream&, std::ofstream&)': driver.cpp:63: error: no matching function for call to std::basic_ifstream>::open(std::string&)'中../include/c++/3.4.2/fstream:570:注意:候选为:void std::basic_ifstream&lt_CharT,_Traits>::打开(const char*,std::_Ios_Openmode)[其中_CharT=char,_Trait=std::char_Traits]J: \Class_Files_2013_Fall\Advanced C++\Week1\Lab_2(Letter_Counter)\driver.cpp:68:错误:没有用于调用"std::basic_ofstream>::open(std::string&)"的匹配函数../include/c++/3.4.2/fstream:695:注意:候选为:void std::basic_ofstream&lt_CharT,_Traits>::打开(const char*,std::_Ios_Openmode)[其中_CharT=char,_Trait=std::char_Traits]

所以总的来说,我有:

    ifstream inFile;                    
//defines the file pointer for the text document
    ofstream outFile;                   
//the file pointer for the output file
    openFile(inFile, outFile);          
//allow the user to specify a file for reading and outputting the stats

然后是功能:

void openFile(ifstream& inF, ofstream& outF){
    // Ask the user what file to READ from
    string readFile, writeFile;
    cout << "Enter the name of the file you want to READ from: ";
    cin >> readFile;
    cout << endl;
        // Open the File
    inF.open(readFile);
    // Ask the user what file to WRITE to
    cout << "Enter the name of the file you want to WRITE to: ";
    cin >> writeFile;
    cout << endl;
    outF.open(writeFile);
}

我还实现了:

#include <fstream>

和:

using namespace std;

主要的东西是教练放在那里的,所以我不能改变这些。换句话说,我必须将文件指针传递到openFile函数中,并向用户询问文件的名称。然而,我从未被教导如何做到这一点。一个基本的答案将不胜感激,离开我已经在做的事情。

只有C++11支持用std::string s打开fstream。

编译与C++11兼容的应用程序(取决于编译器,对于clang和gcc,它是-std=c++11),或者将调用更改为inF.open(readFile.c_str());

简单修复:

inF.open(readFile.c_str());
outF.open(writeFile.c_str();

这两个函数都希望您传入一个const char*作为第一个参数。你正试图传递一个字符串。

no matching function for call to std::basic_ifstream::open(std::string&)

当您看到"无匹配函数"错误时,这意味着编译器已搜索但找不到接受您给出的参数的函数。在这种情况下,它无法找到采用std::string&的函数open()的过载。

从C++11开始,输入和输出文件流类提供了它们的构造函数和以std::string为参数的open()成员函数的重载。不幸的是,如果您的编译器不支持C++11,那么您将不得不使用使用const char*的重载。您可以通过调用c_str()方法来获取指向缓冲区的指针:

inF.open(readFile.c_str());   // calls open(const char*)
outF.open(writeFile.c_str()); // calls open(const char*)