繁体   English   中英

为什么将字符串作为文件名而不是char *传递时出现错误?

[英]Why do I get an error when passing a string as a filename, but not a char*?

我知道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,那么在堆栈溢出时应该少一篇文章...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM