谁能告诉我为什么这个方法不能编译?
void Statistics::readFromFile(string filename)
{
string line;
ifstream myfile (filename);
if (myfile.is_open())
{
while (! myfile.eof() )
{
getline (myfile,line);
cout << line << endl;
}
myfile.close();
}
else cout << "Unable to open file";
}
应该有用吧?然而,我总是收到以下错误消息:
Line Location Statistics.cpp:15: error:
no matching function for call to
'std::basic_ifstream<char, std::char_traits<char> >::
basic_ifstream(std::string*)'
任何帮助将不胜感激。
ifstream myfile (filename);
应该:
ifstream myfile (filename.c_str() );
另外,你的读循环逻辑是错误的。它应该是:
while ( getline( myfile,line ) ){
cout << line << endl;
}
您使用的 eof() 函数才有意义after你尝试过阅读一些东西。
要了解为什么会产生影响,请考虑以下简单代码:
int main() {
string s;
while( ! cin.eof() ) {
getline( cin, s );
cout << "line is "<< s << endl;
}
}
如果运行此命令并键入 ctrl-Z 或 ctrl-D 来指示 EOF立即地,即使实际上没有输入任何行(因为 EOF),也会执行 cout。一般来说,eof() 函数不是很有用,您应该测试 getline() 或流提取运算符等函数的返回值。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)