JVE999
JVE999

Reputation: 3517

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

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();
     }


}

Upvotes: 3

Views: 34388

Answers (2)

David G
David G

Reputation: 96810

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

Upvotes: 10

Suvarna Pattayil
Suvarna Pattayil

Reputation: 5239

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;

Upvotes: 2

Related Questions