代码之家  ›  专栏  ›  技术社区  ›  winsmith

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

  •  2
  • winsmith  · 技术社区  · 17 年前

    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*)'
    

    任何帮助都将不胜感激。

    5 回复  |  直到 17 年前
        1
  •  27
  •   anon anon    16 年前
    ifstream myfile (filename);
    

    应该是:

    ifstream myfile (filename.c_str() );
    

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

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

    之后

    要知道为什么会有差别,考虑一下简单的代码:

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

    立即 ,即使没有实际输入任何行(由于EOF),也将执行cout。通常,eof()函数不是很有用,您应该测试函数的返回值,如getline()或流提取运算符。

        2
  •  8
  •   Stack Overflow is garbage    17 年前

    读取编译器错误:

    no matching function for call to 'std::basic_ifstream >::basic_ifstream(std::string*)
    

    No matching function for call to: 它找不到您试图调用的函数

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

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

    由于您没有在上面传递字符串指针,因此您发布的代码必须与实际代码不同。询问代码时始终复制/粘贴。打字错误使问题无法解决。我记得,在任何情况下,构造函数都不接受字符串参数,而只接受常量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));
    }
    
        3
  •  3
  •   Naveen    17 年前

    您应该使用fileName.c_str()以便将const char*指针传递给myFile构造。

        4
  •  3
  •   Bill the Lizard    17 年前

    这个 ifstream 构造函数具有以下签名

    explicit ifstream ( const char * filename, ios_base::openmode mode = ios_base::in );
    

    ifstream ifs ( "test.txt" , ifstream::in );
    

    该模式是可选的,因为它定义了一个默认值,所以您可以使用:

    ifstream myfile ( filename.c_str() );
    
        5
  •  0
  •   user1084944 user1084944    11 年前

    C++11标准解决了这个缺陷。 std::ifstream myfile(filename); 现在应该编译,什么时候 filename 有类型 std::string .