【问题标题】:Attempting to pass string to std::ifstream as argument [duplicate]试图将字符串作为参数传递给 std::ifstream [重复]
【发布时间】:2011-02-24 13:48:18
【问题描述】:

我正在尝试使用从向量中检索到的字符串将文件名传递给 ifstream 以进行打开。

vector<string> files;

//Populate vector

std::ifstream ifile(files[0] ,std::ios::binary);

编译后返回:

错误:没有匹配函数调用 'std::basic_ifstream >::basic_ifstream(std::basic_string, std::allocator >&, const std::_Ios_Openmode&)*

如果我首先尝试将 files[0] 转换为 const char *

vector<string> files;

std::string l = files[0];
const char *p;
p = l.c_str();
std::ifstream ifile(p ,std::ios::binary);

编译器返回:

错误:'l' 未在此范围内声明

我在这里做错了什么?我敢肯定,这是一些基本而引人注目的东西。

【问题讨论】:

  • 我没有重现您的第二个问题(剪切和粘贴您的代码并添加明显缺失的内容)。顺便说一句,您也可以使用 file[0].c_str() 而不是 p。

标签: c++


【解决方案1】:

试试这个:

std::ifstream ifile(files[0].c_str(), std::ios::binary);

【讨论】:

  • 这行得通,但是它后面的代码现在抱怨 ifile 没有在这个范围内声明。 if (!ifile.good()) { 返回 1; }
  • 请注意,您可能还应该检查向量是否为空,否则files[0] 可能会给出运行时错误或异常。
  • 我是个彻头彻尾的白痴,还没写完 if 语句,现在一切正常,谢谢!
  • 当您升级到 C++0x 环境时,您的原始代码应该会神奇地开始工作。
  • 不要劫持这个评论线程,但我注意到将字符串传递给 ifstream 在 gcc 4.4 中有效,但在 4.3 中无法编译。那么这是在 gcc 4.4+ 中添加的 c++0x 功能吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多