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

时间:2014-11-03 15:15:47

标签: c++ c string file-pointer char-pointer

我知道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&amp;)

没有匹配函数

我也试过通过引用和指向字符串的指针传递。 这是因为文件名只被读作char数组,有些是从C?

中删除的

1 个答案:

答案 0 :(得分:4)

这是ifstream上open的签名: -

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,那么堆栈溢出的帖子就会少一些......