我直接从教科书tony gaddis c++中复制了这个问题,但它不会编译。编译器是gcc 5.4.0。这是我的计划:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
string fileName;
char ch;
fstream file;
cout << "enter a filename: ";
cin >> fileName;
file.open(fileName, ios::in);
if(file)
{
file.get(ch);
while(file)
{
cout << ch;
file.get(ch);
}
file.close();
}
else
cout << fileName << " could not be opened.\n";
return 0;
}
同样,我直接将其复制出文本。事实上,在此之后它立即失败:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
string fileName;
char ch;
fstream file;
cout << "enter a filename: ";
cin >> fileName;
file.open(filename, ios::in);
// comment everything else out and compile still fails
return 0;
}
这是控制台中的错误:
chp12chal.cpp: In function ‘int main()’:
chp12chal.cpp:15:32: error: no matching function for call to ‘std::basic_fstream<char>::open(std::
__cxx11::string&, const openmode&)’
file.open(filename, ios::in);
^
In file included from chp12chal.cpp:2:0:
/usr/include/c++/5/fstream:1001:7: note: candidate: void std::basic_fstream<_CharT, _Traits>::open
(const char*, std::ios_base::openmode) [with _CharT = char; _Traits = std::char_traits<char>; std:
:ios_base::openmode = std::_Ios_Openmode]
open(const char* __s,
^
/usr/include/c++/5/fstream:1001:7: note: no known conversion for argument 1 from ‘std::__cxx11::
string {aka std::__cxx11::basic_string<char>}’ to ‘const char*’
所以我不确定这一切意味着什么。虽然我开始将用户输入作为输入流的变量时才开始出现此问题。
当我只是在文件的路径中编码打开它工作正常。
另外,我知道fileName和filename的拼写不一样,但是在很多例子中,这是整本书的完成方式,所以我就这样做了。
这可能是编译器特定的问题吗?
附录:
我也尝试过:
string fileName;
fileName = "chp12txt.txt";
char ch;
fstream file;
file.open(fileName, ios::in);
要排除并仍然得到相同的错误。