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

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

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

问题描述

我正在尝试将一个字符串从 main 传递给另一个函数.这个字符串是需要打开的文本文件的名称.据我所知,我正在传递字符串,但是当我尝试使用 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.

院长

推荐答案

标准流不接受标准字符串,只接受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 打开问题,传递文本文件名的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

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

基础教程推荐