[英]Why do I get an error when passing a string as a filename, but not a char*?
I understand that a char pointer is used to create strings in C
(with a null terminator). 我知道char指针用于在C
创建字符串(带有空终止符)。 But I don't understand why I am getting an error in C++ for passing a string as a file name, yet it works for a char*
. 但是我不明白为什么在C ++中由于将字符串作为文件名传递而出现错误,但是它对于char*
。
The h prototype and cpp function signatures have matched for both scenarios. h原型和cpp函数签名已针对这两种情况进行了匹配。
I have included some code excerpt and all the includes I have for this 'utility' file (I have a few other functions in it besides the read and write ones. 我已经提供了一些代码摘录,以及该“实用程序”文件所包含的所有内容(除读写功能外,我还具有其他一些功能。
//from the header includes
#include <string>
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <limits>
#include <cctype>
#include <cstdlib>
//from the cpp file
//this one throws and error!
void readFiles(string fileName1)
{
ifstream file1;
file1.open(fileName1);
//to do implement read...
}
//This one works
void readFiles(char* fileName1)
{
ifstream file1;
file1.open(fileName1);
//to do implement read...
}
The error I get is: 我得到的错误是:
no matching function for std::basic_ofstream::open(std::string&) 没有与std :: basic_ofstream :: open(std :: string&)匹配的函数
I've also tried passing by reference and pointer to the string. 我也尝试通过引用和指针传递字符串。 Is this because the file name is only read as a char array, some hang over from C? 这是因为文件名仅被读取为char数组,有些仍挂在C上吗?
This is the signature of open on ifstream:- 这是在ifstream上打开的签名:
void open (const char* filename, ios_base::openmode mode = ios_base::in);
So, passing string won't work. 因此,传递字符串将不起作用。
You can do 你可以做
std::string str("xyz.txt");
readFile( str.c_str() )
However, in C++11 there are two overloads:- 但是,在C ++ 11中有两个重载:
void open (const string& filename, ios_base::openmode mode = ios_base::in);
void open (const char* filename, ios_base::openmode mode = ios_base::in);
Had you been with C++11, there would have been one less post on stack overflow... 如果您曾经使用过C ++ 11,那么在堆栈溢出时应该少一篇文章...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.