【问题标题】:c++ error: no matching function for call to 'getline' from within function, but works in mainc++ 错误:没有匹配的函数用于从函数内调用“getline”,但在 main 中有效
【发布时间】:2017-06-07 04:29:34
【问题描述】:

更新:感谢您的建议!从我的函数参数中删除 const 并将 #include 替换为 #include ,成功了!


我是 C++ 新手,我已经查阅了几篇文章,但似乎无法弄清楚为什么我在用户定义的函数中收到“错误:没有匹配的函数调用 'getline'” , 当它从主函数正常工作时。

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

一直在绞尽脑汁寻找解决方案,如果有人能指出我遗漏了什么,我将不胜感激。对不起,如果这是一个幼稚的问题!

精简代码:

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

    }

【问题讨论】:

  • 你忘了#include &lt;string&gt;

标签: c++ c++11


【解决方案1】:

您无法读取const 对象。

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

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

另外,正如评论中提到的,不要忘记添加

#include <string>

【讨论】:

    猜你喜欢
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 2017-10-16
    • 2018-10-09
    • 2011-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多