user2597522
user2597522

Reputation: 23

File I/O error with getline()

My code:

void listall()
{
    string line;
    ifstream input;
    input.open("registry.txt", ios::in);

    if(input.is_open())
    {
        while(std::getline(input, line, "\n"))
        {
            cout<<line<<"\n";
        }
    }
    else
    {
        cout<<"Error opening file.\n";
    }
}

I’m new to C++, and I want to print out a text file line-by-line. I’m using Code::Blocks.

The error it gives me is:

error: no matching function for call to 'getline(std::ifstream&, std::string&, const char [2])'

Upvotes: 2

Views: 2569

Answers (2)

user123
user123

Reputation: 9061

These are the valid overloads for std::getline:

istream& getline (istream&  is, string& str, char delim);
istream& getline (istream&& is, string& str, char delim);
istream& getline (istream&  is, string& str);
istream& getline (istream&& is, string& str);

I'm sure you meant std::getline(input, line, '\n')

"\n" is not a character, it's an array of characters with a size of 2 (1 for the '\n' and another for the NUL-terminator '\0').

Upvotes: 4

Kerrek SB
Kerrek SB

Reputation: 477640

Write this:

#include <fstream>    // for std::ffstream
#include <iostream>   // for std::cout
#include <string>     // for std::string and std::getline

int main()
{
    std::ifstream input("registry.txt");

    for (std::string line; std::getline(input, line); ) 
    {
         std::cout << line << "\n";
    }
}

If you want the error check, it is something like this:

if (!input) { std::cerr << "Could not open file.\n"; }

Upvotes: 1

Related Questions