C++如何将变量用于 ifstream

C++ how do i use a variable for ifstream

本文关键字:用于 ifstream 变量 C++      更新时间:2023-10-16
void searchString(const string selection,const string filename)
{
    ifstream myfile;
    string sline;
    string sdata;
    myfile.open(filename);
    while(!myfile.eof())
    {
        getline(myfile,sline);
        sdata = sdata + sline;
    }

如何使用字符串文件名作为myfile.open(文件名(

最初我使用的是 file.txt,但是如果我使用由函数传入的变量,例如字符串文件名,它会给我一个错误

myfile.open("file.txt");

错误消息如下:

main.cpp:203:25: error: no matching function for call to ‘std::basic_ifstream<char>::open(const string&)’
main.cpp:203:25: note: candidate is:
/usr/include/c++/4.6/fstream:531:7: note: void std::basic_ifstream<_CharT, _Traits>::open(const char*, std::ios_base::openmode) [with _CharT = char, _Traits = std::char_traits<char>, std::ios_base::openmode = std::_Ios_Openmode]
/usr/include/c++/4.6/fstream:531:7: note:   no known conversion for argument 1 from ‘const string {aka const std::basic_string<char>}’ to ‘const char*’
make: *** [main.o] Error 1

std::ifstream::open的构造函数(针对您正在使用的特定C++标准(不允许std::string参数,因此您必须使用:

 myfile.open(filename.c_str());

构造函数需要可以使用其 c_str() 成员函数从 std::string 对象获取的类型 const char *