getline() method no instance of overloaded function

江枫思渺然 提交于 2019-12-14 03:34:34

问题


I am having some problem when trying to do classes for C++. This is my header file.h:

#include <iostream>
#include <string>
#ifndef MESSAGES__H__
#define MESSAGES__H__

class Message
{
    public:
        Message(std::string recipient, std::string sender);
        void append(std::string text);
        std::string to_string() const;
        void print() const;
    private:
        std::string recipient;
        std::string sender;
        std::string message;
        std::string text_input;
        char* timestamp;
};

#endif

And when I run the main method, the getline(cin,) is giving me some error message:

int main()
{
    vector <Message*> message_list;
    Message* message1 = new Message("Student1", "Gabriel");
    cout << "Enter message text line, enter . on new line to finish: " << endl;
    while(getline(cin, text_input))
    {
    }
}

The getline method is giving me no instance of overloaded function. Also, from the same line, the text_input is showing identifier is undefined. I thought I declared in .h class already?

Thanks in advance.

Updated portion

Now all the error has been fixed:

vector <Message*> message_list;
Message* message1 = new Message("Saiful", "Gabriel");
cout << "Enter message text line, enter . on new line to finish: " << endl;
while(getline(cin, message1->get_text_input()))
{
    if(message1->get_text_input() == ("."))
    {
        break;
    }
    else
    {
        message1->append(message1->get_text_input());
    }
}

Inside the while loop, once "." is detected at the beginning of the new line, it supposingly will stop. However, no matter how many times I entered "." at the new line, it just keep prompting. Anybody know why?


回答1:


To fix "text_input is showing identifier is undefined"

You need to change

 while(getline(cin, text_input))

to

 while(getline(cin, message1->text_input))

Possibly this will fix the first error.




回答2:


Try changing your loop like this:

while(getline(cin,&message1->text_input)) 
{

}

If I remember correctly, getline function looks like this:

getline(isstream& stream, string& string)



回答3:


It feels as if you are over complicating things. Just use a temporary variable in getline. If the input is a "." then break, otherwise append the line to the Message object. As a consequence, you should be able to remove the text_input member variable from your Message header file.

std::vector<Message*> message_list;
Message* message1 = new Message("Saiful", "Gabriel");
std::cout << "Enter message text line, enter . on new line to finish: " << std::endl;
std::string input = "";
while(getline(std::cin, input))
{
    if(input == ".")
    {
        break;
    }
    else
    {
        message1->append(input);
    }
}


来源:https://stackoverflow.com/questions/17362152/getline-method-no-instance-of-overloaded-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!