use*_*632 13 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;
}
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)
最后是DataReader.cpp
#include "DataReader.h"
using namespace std;
vector<Data*> DataReader(string textFile)
{
ifstream aStream;
aStream.open(textFile); //line 11
Run Code Online (Sandbox Code Playgroud)
我查找了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>]
Run Code Online (Sandbox Code Playgroud)
提前感谢您的任何意见/建议.
院长
Ara*_*raK 48
标准流不接受standard string,只有c-string!所以传递字符串使用c_str():
aStream.open(textFile.c_str());
Run Code Online (Sandbox Code Playgroud)