g ++坚持寻找stdio.h getline而不是std :: getline(string)

时间:2018-12-04 19:31:06

标签: c++ std iostream ifstream getline

我的程序的一部分:

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

istringstreamifstream均为istream,但是在read_input_file中它尝试将getlinestdio.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**’
...

任何想法为何匹配错误的候选人,而不是std::getline

1 个答案:

答案 0 :(得分:1)

您的问题是inputFile中的constread_input_fileinputFile需要由getline进行修改,因此不会有占用const ifstream&的重载。不幸的是,编译器通过提供帮助并向您显示其他可能的重载,并没有使您意识到这一事实。