我知道char指针用于创建字符串C
(带有空终止符)。但是我不明白为什么我在C ++中由于将字符串作为文件名传递而出现错误,但是它适用于char*
。
h原型和cpp函数签名已针对这两种情况进行了匹配。
我已经提供了一些代码摘录,以及该“实用程序”文件所包含的所有内容(除读写功能外,我还包含其他一些功能)。
//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...
}
我得到的错误是:
没有与std :: basic_ofstream :: open(std :: string&)匹配的函数
我也尝试通过引用和指针传递给字符串。这是因为文件名仅被读取为char数组,有些仍被C挂掉了吗?
这是在ifstream上打开的签名:-
void open (const char* filename, ios_base::openmode mode = ios_base::in);
因此,传递字符串将不起作用。
你可以做
std::string str("xyz.txt");
readFile( str.c_str() )
但是,在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);
如果您曾经使用过C ++ 11,那么堆栈溢出上的帖子就会少一些...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句