c++:ifstream打开问题,为文本文件名传递字符串

标签 c++ string parameters text-files

我正在尝试将字符串从 main 传递到另一个函数。此字符串是需要打开的文本文件的名称。据我所见,我传递的字符串很好,但是当我尝试使用 ifstream.open(textFileName) 时,它并不能正常工作。但是当我手动将其硬编码为 ifstream.open("foo.txt") 时,它工作得很好。我需要多次使用这个函数,所以我希望能够传入一串文本文件名..

这是我的主要内容

#ifndef DATA_H
#define DATA_H
#include "Data.h"
#endif

#ifndef DATAREADER_H
#define DATAREADER_H
#include "DataReader.h"
#endif

using namespace std;

int main()
{
 vector<Data*> database = DataReader("foo.txt");

 return 0; 
}

DataReader 的头部

#include <fstream>
#include <iostream>
#include <vector>
#include <string>

#ifndef DATA_H
#define DATA_H
#include "Data.h"
#endif

using namespace std;

vector<Data*> DataReader(string textFile);

最后是 DataReader.cpp

#include "DataReader.h"

using namespace std;

vector<Data*> DataReader(string textFile)
{
 ifstream aStream;     
 aStream.open(textFile); //line 11

我查找了 ifstream.open() ,它接受一个字符串和一个模式作为参数。不太确定如何处理这些模式,但我尝试了它们,但它们给出了相同的错误消息

DataReader.cpp: In function 'std::vector<Data*, std::allocator<Data*> > DataReader(std::string)':
DataReader.cpp:11: error: no matching function for call to 'std::basic_ifstream<char, std::char_traits<char> >::open(std::string&)'
/usr/local/lib/gcc/sparc-sun-solaris2.9/4.0.3/../../../../include/c++/4.0.3/fstream:495: note: candidates are: void std::basic_ifstream<_CharT, _Traits>::open(const char*, std::_Ios_Openmode) [with _CharT = char, _Traits = std::char_traits<char>]

提前感谢您的任何意见/建议。

院长

最佳答案

标准流不接受标准字符串,只接受c-string!所以使用 c_str() 传递字符串:

aStream.open(textFile.c_str());

关于c++:ifstream打开问题,为文本文件名传递字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1662624/

相关文章:

C++ rand() 奇怪的行为

C++ 映射插入

c++ - 在 C++ 中解析 .dat 文件

sql-server - 替换单个字符的模式

javascript - 使用 .innerHTML 向 JS 函数发送参数

c++ - 当路径不存在时,Xerces XPath 会导致段错误

c++ - 通过另一个 vector 推力访问 vector 元素

regex - 如何在 Scala 中识别表情符号?

c++ - 函数参数 : accepting a null value also

php - 这个函数是不是参数太多了?