Search code examples
c++stdiostreamifstreamgetline

g++ insists looking to stdio.h getline instead of std::getline (string)


A part of my program:

#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>

using namespace std;


/* Works for istringstream */
void func(const string& text) {
    istringstream ff(text);
    string s;

    getline(ff, s, '-');
}


/* Doesnt work for ifstream */
void read_input_file(const ifstream& inputFile) {
    string s;

    getline(inputFile, s, '\n');
}


int main(int argc, char * argv[]){

    ifstream inputfile;
    ofstream outputFile;

    inputfile.open(argv[1], ifstream::in);
    if (!inputfile.is_open()) 
        return -1;

    read_input_file(inputfile);

    inputfile.close();

    return 0;
}

Both istringstream and ifstream are istream, however in read_input_file it tries to match getline with the one defined from stdio.h...

test.cpp:23:28: error: no matching function for call to ‘getline(const ifstream&, std::__cxx11::string&, char)’

  getline(inputFile, s, '\n');

g++ -Wall -c "test.cpp" 

test.cpp: In function ‘void read_input_file(const ifstream&)’:
test.cpp:23:28: error: no matching function for call to ‘getline(const ifstream&, std::__cxx11::string&, char)’
  getline(inputFile, s, '\n');
                            ^
In file included from /usr/include/c++/8/cstdio:42,
                 from /usr/include/c++/8/ext/string_conversions.h:43,
                 from /usr/include/c++/8/bits/basic_string.h:6400,
                 from /usr/include/c++/8/string:52,
                 from /usr/include/c++/8/bits/locale_classes.h:40,
                 from /usr/include/c++/8/bits/ios_base.h:41,
                 from /usr/include/c++/8/ios:42,
                 from /usr/include/c++/8/ostream:38,
                 from /usr/include/c++/8/iostream:39,
                 from test.cpp:1:
/usr/include/stdio.h:622:18: note: candidate: ‘__ssize_t getline(char**, size_t*, FILE*)’
 extern __ssize_t getline (char **__restrict __lineptr,
                  ^~~~~~~
/usr/include/stdio.h:622:18: note:   no known conversion for argument 1 from ‘const ifstream’ {aka ‘const std::basic_ifstream<char>’} to ‘char**’
...

Any ideas why matching the wrong candidate, instead of std::getline


Solution

  • Your problem is inputFile is const in read_input_file. inputFile needs to be modified by getline so there is no overload that takes an const ifstream&. Unfortunately the compiler, by being helpful and showing you other possible overloads, doesn't make you aware of this fact.