发现此文件中的错误读取代码(C++)

win*_*ith 2 c++ file-io

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

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

}
Run Code Online (Sandbox Code Playgroud)

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

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

任何帮助将不胜感激.

小智 26

ifstream myfile (filename);
Run Code Online (Sandbox Code Playgroud)

应该:

ifstream myfile (filename.c_str() );
Run Code Online (Sandbox Code Playgroud)

此外,您的读循环逻辑是错误的.它应该是:

while ( getline( myfile,line ) ){
   cout << line << endl;
}
Run Code Online (Sandbox Code Playgroud)

您正在使用的eof()函数仅您尝试读取某些内容后才有意义.

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

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

如果你运行它并输入ctrl-Z或ctrl-D来立即指示EOF ,即使没有实际输入任何行(因为EOF),也会执行cout.通常,eof()函数不是很有用,您应该测试getline()或流提取运算符等函数的返回值.


jal*_*alf 8

阅读编译器错误:

no matching function for call to 'std::basic_ifstream >::basic_ifstream(std::string*)
Run Code Online (Sandbox Code Playgroud)

No matching function for call to: 它无法找到您要调用的功能

std::basic_ifstream >:: - ifstream的成员函数

:basic_ifstream(std::string*) - 以字符串指针作为参数的构造函数

因此,您尝试通过将字符串指针传递给其构造函数来创建ifstream.它找不到接受这种参数的构造函数.

由于您没有在上面传递字符串指针,因此您发布的代码必须与实际代码不同.在询问代码时始终复制/粘贴.错别字使得无法弄清楚问题.无论如何,我记得,构造函数不接受字符串参数,只接受const char*.所以filename.c_str()应该做的伎俩

除此之外,你可以更简单地做到这一点:

ifstream myfile (filename);
    std::copy(std::istream_itrator<std::string>(myfile),
              std::istream_itrator<std::string>(),
              std::ostream_iterator<std::string>(std::cout));
}
Run Code Online (Sandbox Code Playgroud)