gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 04:28:36 27 4
gpt4 key购买 nike

我的程序的一部分:

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

两者都是istringstreamifstreamistream,但是在 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

最佳答案

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

关于c++ - g++ 坚持寻找 stdio.h getline 而不是 std::getline (string),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53620152/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com