2

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

3
  • Have you tried looking at a reference for it? You'd find a type mismatch in that and the error messages, and the fact that the default delimiter is a newline. Commented Jul 18, 2013 at 23:27
  • 1
    Try putting the newline in single quotes in the call to getline. It takes a char, not a string. And make sure you #include <iostream> and #include <string>. Commented Jul 18, 2013 at 23:27
  • @aet Thanks, that actually worked. Shouldve known that it was trying to tell me that it wanted a char, if i tried to analyze it just a little more i probably couldve figured it out. Thanks. Commented Jul 18, 2013 at 23:36

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

I saw aet's comment first, his (or hers) fix worked. However you stated the same thing, so ive got to give you credit. Resolved.
1

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

2 Comments

What does std::cerr do?
@user2597522 there's the standard out stream which can be written to with std::cout and the standard error stream which can be written to with std::cerr. It is advisable to write error the std::cerr so that you can distinguish between normal program flow and error messages when running. For example ./a.out > /dev/null will throw away everything written to standard out. ./a.out 2 > errors.txt will write all erorr text to "errors.txt"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.