C++ 没有重载函数 getline 的实例匹配参数列表

问题描述 投票:0回答:3

我正在编写一个程序,需要将 cin 的输入读入一个字符串。当我尝试使用常规 getline(cin, str) 时,它会无休止地提示输入,并且永远不会移动到下一行代码。所以我查看了我的教科书,它说我可以将 cstring 和字符串的大小以 cin.getline(str, SIZE) 的形式传递给 getline。但是,当我这样做时,出现错误“没有重载函数 getline 的实例与参数列表匹配。

我四处搜索,但我发现的只是人们说使用导致无限输入提示的 getline(cin,str) 形式,或者建议我正在学习的类中可能有两个具有不同参数的不同 getline 函数包括,我需要告诉 IDE 使用正确的(我不知道该怎么做)。

这是我在文件开头包含的内容:

#include <string>
#include <array>
#include <iostream>
#include "stdlib.h"
#include "Bank.h"   //my own class

using namespace std;

这是代码的相关部分:

        const int SIZE = 30; //holds size of cName array
        char* cName[SIZE];   //holds account name as a cstring   (I originally used a string object in the getline(cin, strObj) format, so that wasn't the issue)
        double balance;      //holds account balance

        cout << endl << "Enter an account number: ";
           cin >> num;       //(This prompt works correctly)
        cout << endl << "Enter a name for the account: ";
           cin.ignore(std::numeric_limits<std::streamsize>::max()); //clears cin's buffer so getline() does not get skipped   (This also works correctly)
           cin.getline(cName, SIZE); //name can be no more than 30 characters long   (The error shows at the period between cin and getline)

如果相关的话,我正在使用 Visual Studio C++ 2012

c++ visual-studio-2012
3个回答
2
投票

这是违规行:

char* cName[SIZE];

你真正需要的是:

char cName[SIZE];

然后,你应该可以使用:

cin.getline(cName, SIZE);

2
投票

来自 visual studio 的这个错误信息非常具有误导性。实际上对我来说,我试图从 const 成员函数调用一个非 const 成员函数。

class someClass {
public:
    void LogError ( char *ptr ) {
        ptr = "Some garbage";
    }
    void someFunction ( char *ptr ) const { 
        LogError ( ptr );
    }
};
int main ()
{
    someClass obj;
    return 0;
}

0
投票

与 R Sahu 的答案相关,编译器给出了参数不匹配的线索。这确实有点误导,因为参数不在 paranthesys 中,而是在显式参数列表之外。如果你添加一个 const 函数,那么歧义就解决了,编译器会找到要调用的东西。 尝试以下代码,它不会给出错误并使错误消息更加清晰。

    #include <iostream>

    class someClass {
    public:
        void LogError(char* ptr) {
            std::cout << "LogError: before arg=" << ptr << "\n";
            ptr[0] = 0;
            std::cout << "LogError: after arg=" << ptr << "\n";
        }
        void LogError(char* ptr) const {
            std::cout << "const LogError: arg=" << ptr << "\n";
        }
        void ROFunction(char* ptr) const {
            LogError(ptr);
        }
        void RWFunction(char* ptr) {
            LogError(ptr);
        }
    };
    int main()
    {
        char s[] = "test";
        someClass obj;
        obj.ROFunction(s);
        obj.RWFunction(s);
        obj.ROFunction(s);
        return 0;
    }

随着输出:

const LogError: arg=test
LogError: before arg=test
LogError: after arg=
const LogError: arg=

© www.soinside.com 2019 - 2024. All rights reserved.