C++-将文件处理程序传递到函数中以打开时出错
C++ - Error passing file handlers into function for opening
我有几个错误我不明白,甚至不知道如何在互联网上搜索。我尝试过"用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<_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<_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*)
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- 使用dynamic_cast和构造函数时出错
- CHECK(调用)函数在Google Colab中出错
- 从R调用C++函数并对其进行集成时出错
- 这个函数哪里出错了
- PrintWindow函数在notepad.exe中出错
- 使用运算符调用 void 函数时出错<set>
- 为 NewObjectA() 函数创建 jvalues 的参数数组时出错 - JNI Invocation API
- 在定义的函数中使用常量时出错
- 将成员函数作为构造函数参数调用时出错 "Variable is not a type name"
- 使用根/C++时出错:没有匹配的构造函数来初始化'TTree'
- Arduino IDE 中使用 strncmp 函数时出错
- 从DLL导出函数,LoadLibrary()需要用TEXT转换的字符串才能编译而不会出错
- 编译包含指向模板函数的指针的初始值设定项列表时,gcc 出错,但 clang 不出错
- 使用一个参数的模板函数时出错(适用于 2)
- 为什么 stl 字符串C++函数有时出错有时会出错?
- 使用类的构造函数时出错
- 在 c++ 的构造函数中分配对象向量时出错
- 为什么在函数参数前面添加 const 会出错?
- 调用析构函数时出错