簡體   English   中英

沒有重載的實例 function “getline”匹配參數列表——參數類型是:(std::ifstream,char)

[英]no instance of overloaded function "getline" matches the argument list -- argument types are: (std::ifstream,char)

beginner c++ user here 我試圖從文件中獲取行並將其放入字符串數組中。 該文件的每個單詞都在其自己的行中。 每當我測試數組時,它似乎正在將每個字母加載到數組中。 所以它是字符而不是每個單詞作為一個字符串。 每個文件中的第一件事是一個數字,它將是數組的大小。 我應該動態分配數組,我相信我做對了。 歡迎任何幫助。 我正在使用 VScode,getline 給我的問題是,沒有重載 function“getline”的實例與參數列表匹配——參數類型是:(std::ifstream,char)。

   #include <iostream>
   #include <fstream>
   #include <string>

   using namespace std;

   int showMenuGetChoice();
   string createStringArray(int);
   void getInfoFromUser(string, string, int);
   void printStory(int, string, int);

   // Calls all the other functions to make a working Madlibs game. 
 int main ()
 {
    int UserChoice;

    ifstream QuestionFile;
    int arraySize;
    string Question;
    int test = 0;
    do {

    cout <<"Let's Play some Madlibs!!" << endl << endl;
    UserChoice=showMenuGetChoice();

    if (UserChoice == 1)
    {
        ifstream QuestionFile;
        QuestionFile.open("starWars.txt");
        QuestionFile >> arraySize;
        cin.ignore();

        string QuestionArray=createStringArray(arraySize);

        if(QuestionFile.is_open())
        {
            QuestionArray[arraySize];

            for(int i=0; i < arraySize; i++)
            {
                getline(QuestionFile, QuestionArray[i]);
            }
        }
        for(int i=0; i < arraySize; i++)
        {
            cout << QuestionArray[i] << endl;
        }

      }

// Takes in a integer and creates a array of that size. Dynamically allocates the array and returns a point to this array.
string createStringArray(int n)
{
    string*QuestionArray = new string[n];

    return *QuestionArray;
}

你收到錯誤:

沒有重載的實例 function “getline”匹配參數列表——參數類型是:(std::ifstream,char)。

由於您的“getline”調用有問題:

getline(QuestionFile, QuestionArray[i]);

std::getline接受兩個參數,一個std::istream引用和一個std::string引用。 QuestionFile是一個istream ,所以沒關系,但是如果您查看QuestionArray的聲明:

string QuestionArray=createStringArray(arraySize);

您應該注意到 QuestionArray 是一個string類型的變量。 我不認為這是你想要的。 您應該始終謹慎選擇您在 C++ 中聲明的變量類型,否則您將違背編譯器試圖為您提供的類型安全。

字符串QuestionArray的第i個元素是一個char ,而不是一個string 這是編譯器錯誤的原因。 您試圖將行放入單個字符元素而不是字符串中。

希望有了上面的解釋,提供的編譯器消息現在會更有意義。 它提供相同的信息,只是更簡潔一點。

有了這些知識,讓我們解決createStringArray function:

string createStringArray(int n)
{
    string*QuestionArray = new string[n];

    return *QuestionArray;
}

當我希望 function 返回字符串序列時,您聲明 function 返回單個字符串。 返回字符串序列的正確方法是使用std::vector<std::string> ,但是如果你必須使用有風險的、過時的、手動的 memory 管理,你需要返回一個指向字符串的指針,而不是來自這個 function。有了這些知識,你應該能夠更正這個 function,原始的QuestionArray變量類型,並且編譯器錯誤應該 go 消失。

暫無
暫無

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

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