c ++:ifstream打开传递文本文件名的字符串的问题 [英] c++: ifstream open problem with passing a string for text file name

查看:596
本文介绍了c ++:ifstream打开传递文本文件名的字符串的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图传递一个字符串从main到另一个函数。此字符串是需要打开的文本文件的名称。只要我可以看到,我传递字符串alright,但当我尝试使用 ifstream.open(textFileName),它不工作。但是当我手动硬编码为 ifstream.open(foo.txt),它工作正常。我需要使用这个函数几次,所以我想能够传递一个文本文件名的字符串..

i'm trying to pass a string from main to another function. this string is a name of text file that needs to be oepened. as far as i can see, i am passing the string alright, but when i try to use ifstream.open(textFileName), it doesn't quite work. but when i manually hardcode it as ifstream.open("foo.txt"), it works just fine. i would need to use this function several times so i would like to be able to pass in a string of text file name..

这里是我的主

#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的标题

header of 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

and finally the DataReader.cpp

#include "DataReader.h"

using namespace std;

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

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

i looked up the ifstream.open() and it takes a string and a mode as parameters. not really sure what to do with the modes, but i tried them but they gave the same error message

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>]

预先感谢您提供任何意见或建议。

thank you in advance for any input/suggestions.

Dean

推荐答案

标准流不接受标准字符串,只有 c-string !因此,使用 c_str()

the standard streams doesn't accept a standard string, only c-string! So pass the string using c_str():

aStream.open(textFile.c_str());

这篇关于c ++:ifstream打开传递文本文件名的字符串的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆