C++我如何为ifstream使用变量

标签 c++

<分区>

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(filename)

最初我使用的是 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());

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

关于C++我如何为ifstream使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11681528/

相关文章:

c++ - 崩溃后检查 gdb 回溯中的 C++ 对象

c++ - 如何使用 std::tuple 的值作为参数调用函数?

c++ - CPU 数量的增加会降低性能,CPU 负载不变并且没有通信

c++ - 为什么会崩溃?

c++ - C++ 中的 int 和 const int

c++ - 测试两个 valarray<double> 相等的最佳方法?

java - 如何在 Java 中将有符号 16 位整数转换为无符号 16 位整数?

c++ - 重载基类函数

c++ - 继承类的数组

c++ - 解析包含处理指令的 XML