问题
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