-1

我知道 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 吗?

4

1 回答 1

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,就会少一篇关于堆栈溢出的帖子……

于 2014-11-03T15:19:44.137 回答