ifstream :: open()函数使用字符串作为参数 [英] ifstream::open() function using a string as the parameter
问题描述
我想要一个程序,要求他们用户想要读取的文件,当我尝试 myfile.open(fileName)
I得到错误:没有匹配函数调用 std :: basic_ifstream< char,std :: char_traits< char>> :: open(std :: string&)'
。
I'm trying to make a program that asks for the file that they user would like to read from, and when I try to myfile.open(fileName)
I get the error: "no matching function for call to std::basic_ifstream<char, std::char_traits<char> >::open(std::string&)'
" at that line.
string filename;
cout<<"Enter name of file: ";
cin>>filename;
ifstream myFile;
myFile.open(filename); //where the error occurs.
myFile.close();
推荐答案
在上一个版本的C ++ ), open()
仅对第一个参数使用 const char *
,而不是 std :: string
。正确的调用方式是:
In the previous version of C++ (C++03), open()
takes only a const char *
for the first parameter, instead of std::string
. The correct way of calling it would then be:
myFile.open(filename.c_str());
在当前C ++(C ++ 11)中,代码很好,告诉您的编译器启用对它的支持。
In current C++ (C++11) that code is fine, though, so see if you can tell your compiler to enable support for it.
这篇关于ifstream :: open()函数使用字符串作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!