Serial problem

void loop ()
{
  char character;
  String content = "";
  if(Serial.available() >0 )
  {
    while(Serial.available()) 
    {
      character = Serial.read();
      content = content + character;
    }
    Serial.println(content);
  }
}

So this morning I have been playing around with serial. I want to use serial sent strings in my program. So using the above code, it combines all the cars sent into one string which I then send back to see the result.

here is the outcome: When I send a I get back a when I send ab I get back two lines a and then b. If I send a sentence EG 'Arduino Is Great' here is the outcome: A r dun io Is Great

http://gyazo.com/54a1f3bd5e62e34ef0852658253d9102

Why do I have this problem? How can I solve it? Thank you Trevor B

TrevorB: Why do I have this problem?

You're assuming that when you hit enter, every character instantly appears in the buffer. In actuallity, the loop() function can run 100s of times in between when the characters are received.

TrevorB: How can I solve it?

The improper way to do it would be to add a delay to allow all the characters to come through. I'm sure Zoomkat will be along soon to post an example. The proper way to do it, is to use a terminating character to identify when the string is finished, and only print it out after you receive that character.

How very interesting! I totally forgot about that. Ok I do understand whats been happening. At the moment I just added a second delay It seems to be working.

The proper way you say sounds very clever, though I think for my purposes at the moment, I shall be fine. Though If he does post a relpy, I would love to see the coded example. Thank you for quick response! Thanks again Trev