c ++错误:没有匹配函数从函数内调用'getline',但在main中工作

时间:2017-06-07 04:29:34

标签: c++ c++11

更新:感谢您的建议!从我的函数参数中删除const并用#include替换#include,work!

我是C ++的新手,我查了几篇帖子,但似乎无法弄清楚为什么我从我的用户定义的函数中得到一个“错误:没有匹配函数来调用'getline'” ,当它从主要功能正常工作时。

我也不明白为什么在一些例子中,我在网上看到getline需要2个参数(std :: istream&,std :: string&)而在其他例子中它需要3个参数(std :: istream&, std :: string&,char)

一直在绞尽脑汁寻求解决方案,如果有人能指出我所缺少的东西,我真的很感激。对不起,如果这是一个天真的问题!

简明代码:

 #include <stdlib.h>
 #include <stdio.h>
 #include <string.h>
 #include <fstream>
 #include <iostream>
 #include <cstdlib> 

 using namespace std;

 char *myfunction (std::ifstream& infile, const std::string& strBuf){

        //compile error "no matching function for call to 'getline'"
        getline(infile, strBuf);  

        char *ptr= NULL;
        return ptr;
    }



  int main() {
        ifstream infile; 
        infile.open("myfile"); 
        std::string strBuf;

        getline(infile, strBuf);
        // prints the first line of the file as expected
        cout << strBuf << endl;  

    }

1 个答案:

答案 0 :(得分:4)

您无法读取const个对象。

将参数类型从const std::string&更改为std::string&

char *myfunction (std::ifstream& infile, std::string& strBuf)
                                     // ^^ No const 
{
    getline(infile, strBuf);
    ...
}

此外,正如评论中所述,请勿忘记添加

#include <string>