【问题标题】:ifstream::open() function using a string as the parameter [duplicate]ifstream::open() 函数使用字符串作为参数[重复]
【发布时间】:2013-03-02 21:59:35
【问题描述】:

我正在尝试编写一个程序来询问他们用户想要读取的文件,当我尝试 myfile.open(fileName) 时,我收到错误:“没有匹配函数调用 std::basic_ifstream<char, std::char_traits<char> >::open(std::string&)'”在那条线。

string filename;
cout<<"Enter name of file: ";
cin>>filename;
ifstream myFile;
myFile.open(filename); //where the error occurs.
myFile.close();

【问题讨论】:

  • 令人讨厌的是,cplusplus.com 没有提到自 C++11 以来open 有一个string 重载,而 cppreference.com 确实 确实说明了这一点。

标签: c++ string fstream ifstream


【解决方案1】:

在以前的 C++ 版本(C++03)中,open() 的第一个参数只采用 const char *,而不是 std::string。正确的调用方式是:

myFile.open(filename.c_str());

不过,在当前的 C++ (C++11) 中,该代码是可以的,所以看看您是否可以告诉您的编译器启用对它的支持。

【讨论】:

  • 甚至 CodeBlocks 也不支持将字符串变量传递给“open”方法。必须使用“.c_str()”才能工作。
最近更新 更多