【发布时间】:2009-11-02 17:36:18
【问题描述】:
我正在尝试将字符串从 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>]
提前感谢您的任何意见/建议。
院长
【问题讨论】:
-
如果您将包含保护器放入它们要保护的标头中,您会在生活中获得更大的成功。包含标题应该像单个
#include行一样简单,而不是有条件地包含它的四行,您需要知道每个标题的保护符号的名称。每个标题的前两行是#ifndef/#define,最后一行是#endif。你应该能够在你见过的 every 标题中找到这样的例子。
标签: c++ string parameters text-files