点击这个文件中的错误读取代码(C ++) [英] Spot the error in this file reading code (C++)

查看:116
本文介绍了点击这个文件中的错误读取代码(C ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以告诉我为什么这个方法不会编译?

  void Statistics :: readFromFile b $ b {
string line;
ifstream myfile(filename);
if(myfile.is_open())
{
while(!myfile.eof())
{
getline(myfile,line);
cout<<线<< endl;
}
myfile.close();
}

else cout<< 无法打开文件;

}

应该工作,对吗?但是,我总是收到以下错误消息:



 
行位置Statistics.cpp:15:错误:
没有匹配的函数调用
'std :: basic_ifstream< char,std :: char_traits< char>> ::
basic_ifstream(std :: string *)'



$ b < >解决方案

  ifstream myfile(filename); 

应为:

  ifstream myfile(filename.c_str()); 

此外,你的读循环逻辑是错误的。应为:

  while(getline(myfile,line)){
cout<线<< endl;
}

您使用的eof 您尝试阅读阅读内容。



要了解为什么会产生影响,请考虑以下简单代码:

  int main(){
string s;
while(!cin.eof()){
getline(cin,s);
cout<< line is<< s<< endl;
}
}



如果运行此类型并键入ctrl-Z或ctrl -D立即指示EOF ,即使没有实际输入线(因为EOF),cout也将被执行。一般来说,eof()函数不是非常有用,你应该测试函数的返回值,如getline()或流提取运算符。


Can anyone please tell my why this method won't compile?

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"; 

}

Should work, right? Yet, I always get the following error message:

Line Location Statistics.cpp:15: error:
   no matching function for call to
   'std::basic_ifstream<char, std::char_traits<char> >::
      basic_ifstream(std::string*)'

any help would be greatly appreciated.

解决方案

ifstream myfile (filename);

should be:

ifstream myfile (filename.c_str() );

Also, your read-loop logic is wrong. It should be:

while ( getline( myfile,line ) ){
   cout << line << endl;
}

The eof() function that you are using is only meaningful after you have tried to read read something.

To see why this makes a difference, consider the simple code:

int main() {
    string s; 
    while( ! cin.eof() ) {
    	getline( cin, s );
    	cout << "line is  "<< s << endl;
    }
}

If you run this and type ctrl-Z or ctrl-D to indicate EOF immediately, the cout will be performed even though no line has actually been input (because of the EOF). In general, the eof() function is not very useful, and you should instead test the return value of functions like getline() or the stream extraction operators.

这篇关于点击这个文件中的错误读取代码(C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆