Why is getline() in C++ not working? (no matching function for call to 'getline(std::ofstream&, std::string&)'

人盡茶涼 提交于 2020-08-26 07:15:42

问题


I'm trying to read from a file, but C++ is not wanting to run getline().

I get this error:

C:\main.cpp:18: error: no matching function for call to 'getline(std::ofstream&, std::string&)'
          std::getline (file,line);
                                 ^

This is the code:

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <string>

using namespace std;

int main(){
    string line;

    std::ofstream file;
    file.open("test.txt");
    if (file.is_open())
     {
       while ( file.good() )
       {
         getline (file,line);
         cout << line << endl;
       }
       file.close();
     }


}

回答1:


std::getline is designed for use with input stream classes (std::basic_istream) so you should be using the std::ifstream class:

std::ifstream file("test.txt");

Moreover, using while (file.good()) as a condition for input in a loop is generally bad practice. Try this instead:

while ( std::getline(file, line) )
{
    std::cout << line << std::endl;
}



回答2:


std::getline reads characters from an input stream and places them into a string. In your case your 1st argument to getline is of type ofstream. You must use ifstream

std::ifstream file;


来源:https://stackoverflow.com/questions/18658837/why-is-getline-in-c-not-working-no-matching-function-for-call-to-getline

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!