我正在尝试将字符串从 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/