[Solved] Why is the read input repeated in the string?

I am trying to read from the serial monitor and use the input as a string. However the resultant string, as printed, is the input + the input, ie if I input 12345678 the string printed is 1234567812345678. Could someone please explain why?

Here is the code:

#define STR 8

char theInput[STR];

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

  void loop() {
      int i=0;
      if (Serial.available() >= STR) {
        for (i=0; i<STR; i++) {
        theInput[i]=Serial.read();
        }
                
      Serial.print("OK I received: ");
      Serial.println(theInput);
      }
}

Thanks in advance for any help.

You need room for a terminating "null" byte (0x00). If you are reading 8 bytes, you need an array of 9 to put them in. The final one needs to be 0x00.

You need to terminate the string you received with a '\0' character to signify the end of the string. I think you are just getting some random stuff after the string that happens to be your input string.

Edit: Nick beat me to it!

Printing stuff before (you do that) and after the string (you don’t do that) is a good idea.

Showing the exact output you get is a good idea, too.

      Serial.print("OK I received: [");
      Serial.print(theInput);
      Serial.println("]");

will tell you far more about what is actually happening.