簡體   English   中英

C ++錯誤:沒有匹配的函數可從函數內部調用“ getline”,但可在main中使用

[英]c++ error: no matching function for call to 'getline' from within function, but works in main

更新:感謝您的建議! 從我的函數參數中刪除const並將#include替換為#include,成功了!


我是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;  

    }

您無法讀取const對象。

將參數類型從const std::string&更改為std::string&

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

另外,如評論中所述,別忘了添加

#include <string>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM