0

I am having problem when trying to do pointer loop in C++. What I am trying to do is, user can keep enter message and the message on the new line will be appended. It will only stop prompting when "." is detected at the beginning of a new line. Here is my main method:

vector <Message*> message_list;
Message* message1 = new Message("Student1", "Student2");
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());
    }
}
 }

And this is my .cpp file:

Message::Message(string recipient, string sender)
{
this->recipient = recipient;
this->sender = sender;  
}

string Message::get_text_input()
{
return text_input;
}

void Message::append(string text)
{
message += text + "\n";
}

string Message::to_string() const
{
return ("From: " + sender + "\n" + "To: " + recipient + "\n");
}

void Message::print() const
{
cout << message;
}

My header class:

class Message
{
public:
Message(std::string recipient, std::string sender);
std::string get_text_input();
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;
};

Does anybody know why is it so? Even ".' is detected, it still wont stop.

Thanks in advance.

4
  • getline(cin, message1->get_text_input()) compiles? It should not. Commented Jun 28, 2013 at 11:00
  • 2
    Please don't post under multiple names stackoverflow.com/questions/17362152/… Commented Jun 28, 2013 at 11:02
  • But how should I write getline(cin, text_input)? because I will hit error message if I do this. I will update my header file Commented Jun 28, 2013 at 11:02
  • Hello anybody could help? This shows me no error and I don't even know how to google for answer. Commented Jun 28, 2013 at 11:11

1 Answer 1

1

In the getline(cin, message1->get_text_input()) you get the field text_input returned by value. So now you have a brand new string, in which you fill the message, but it is instantly destroyed, because it never gets a name. To solve your Problem, make get_text_input return a reference:

string& Message::get_text_input()
{
return text_input;
}

That way, the input string will get the line into the original string. Also, go and look up References and Values, you will need them a lot.

Sign up to request clarification or add additional context in comments.

1 Comment

Okay thanks a lot. It's fixed. Unlike somebody at the above comment, they only know how to spot duplicate thread but without helping. Thanks Flonk

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.