【问题标题】:C++ Issue Using Getline使用 Getline 的 C++ 问题
【发布时间】:2017-04-03 02:58:52
【问题描述】:

我正在尝试创建一个程序,用户可以在其中输入一系列球员姓名和分数并将它们读回。但是,我无法使用 getline 存储他们的输入。在 InputData 函数中的 getline 上,Visual Studio 指出,“错误:没有重载函数的实例“getline”与参数列表参数类型匹配:(std::istream, char)”,并且在 == 上,它说,“错误: 操作数类型不兼容(“char”和“const char *”)”。这是我的代码:

#include <iostream>
#include <string>

using namespace std;

int InputData(string [], int [], int);
void DisplayPlayerData(string [], int [], int);

void main()
{
    string playerNames[100];
    int scores[100];

    int sizeOfArray = sizeof(scores);
    int sizeOfEachElement = sizeof(scores[0]);
    int numberOfElements = sizeOfArray / sizeOfEachElement;

    cout << numberOfElements;

    int numberEntered = InputData(playerNames, scores, numberOfElements);

    DisplayPlayerData(playerNames, scores, numberOfElements);

    cin.ignore();
    cin.get();
}

int InputData(string playerNames, int scores[], int size)
{
    int index;


    for (index = 0; index < size; index++)
    {
        cout << "Enter Player Name (Q to quit): ";
        getline(cin, playerNames[index]);
        if (playerNames[index] == "Q")
        {
            break;
        }
        cout << "Enter score: ";
        cin >> scores[index];
    }

    return index;
}

【问题讨论】:

    标签: c++ getline


    【解决方案1】:

    int InputData(string playerNames, int scores[], int size)

    应该是

    int InputData(string playerNames[], int scores[], int size)


    在您的代码中,您将 playerNames 作为字符串而不是字符串数组传递。

    getline(cin, playerNames[index]); playerNames[index] 是一个字符,因为playerNames 是一个字符串。

    【讨论】:

    • 是的,这就是我做错了。非常感谢。
    • 我的荣幸 :) @jackofblaze
    • 我对我的 getline 的另一个问题还有其他问题,我应该在这里提问还是开始一个新的问题?我只是遇到了 getline 在第一次运行后跳过任何用户输入的问题,并一直这样做直到它通过所有数组元素。
    • 我认为你应该开始一个新问题,因为你可以详细描述问题并吸引更多人。@jackofblaze
    【解决方案2】:

    错误:没有重载函数“getline”的实例与参数列表参数类型匹配:(std::istream, char)"

    这意味着您将单个 char 值传递给 getline(),而不是整个 字符串。你这样做:

    getline(cin, playerNames[index])
    

    您将playernames 作为字符串变量而不是sting[] 数组传递。因此,当您执行playernames[index] 时,您是在尝试将单个字符值传递给函数。

    main() 函数中的代码来看,您希望将字符串的数组 传递给函数,而不是只是单个字符串。

    因此,更改InputData()的参数

    int InputData(string playerNames, int scores[], int size)
    

    收件人:

    int InputData(string playerNames[], int scores[], int size)
    

    **@Pinky 比我先发布答案 :),但我想提供更多细节,所以我发布了我的答案。

    另一件事,除了我想指出的主要问题之外,您应该将 main() 函数的返回数据类型从 void main() 更改为 int main()。 p>

    【讨论】:

      【解决方案3】:

      我可能是错的,因为我已经很久没有使用 c++了,但是你有没有尝试过 cin.getline 而不是 getline?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-03-31
        • 2023-03-06
        • 1970-01-01
        • 2011-06-09
        • 1970-01-01
        • 1970-01-01
        • 2013-05-12
        • 2012-09-21
        相关资源
        最近更新 更多