Serial.println char array serial.printing issue

Hello

I'm very new to Arduino and have encountered my first issue which I haven't been able to solve in 2 days. I'm seriously starting to get frustrated. :cry: Hopefully one of you guys could point out where I'm going wrong.

Im making two char arrays: char inputx[3] and char inputy[3]. I get their values from serial.read. After getting the values, printing inputx prints the value AND the serial chars that came after it, and inputy prints out normally.

Here is the code:

char inputx[3];
char inputy[3];

void setup()
{
  Serial.begin(9600);
}

void loop()
{

  while(Serial.read() != '!') 
  {
  }
    
  while (Serial.available() < 6) 
  {
  }
    
    
     for (int x=0; x < 3; x++) 
      {
      inputx[x] = Serial.read(); 
      }
      
      for (int y=0; y < 3; y++) 
      {
      inputy[y] = Serial.read(); 
      }     

Serial.println(inputx);
Serial.println(inputy);
}

For example, I send "!123456" through arduino software to my arduino mega, the arduino returns:
123456 //this is the inputx value incorrectly printed
456 //this is the inputy value correctly printed

This is just weird! :o Sometimes it even adds some freaky letters after the inputx print, and after the inputy print too.

Regards
Henry

Edit:
Couple of example outputs, two show how random they are (both times I sent !123456 to arduino ):
1st time gives lines:
123456N
456V
Then reset and new try gives:
123456H
456O

Then I tried sending the same line !123456 many times, without resetting in middle. Here is what I got.
123456¢
//1st two
456©
123456§& //2nd
456®&
123456ÝD //3rd
456äD
123456AQ //4th
456HQ
123456ýc //5th
456
d

Im obviously doing something silly. ;D

You will need one more byte of storage for the string terminator...

char inputx[[glow]4[/glow]];
char inputy[[glow]4[/glow]];

You will need to terminate the two strings (repeat the changes below for inputy)...

[glow]int x;[/glow]
for (x=0; x < 3; x++)
{
  inputx[x] = Serial.read();
}
[glow]inputx[x] = 0;[/glow]

You can now safely print the two strings.

Coding Badly, Thanks a million! Its working like a charm now. So I forgot to terminate the string and make space for the nul.. a little embarassin. :-[