unable to overwrite a new value in a variable

In the below code, "K" value is not updated ,when I give a second input ..

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

void loop()
{
  
  Serial.print("Enter a No:\n ");
  String source; 
  char sv[2];
 
 readSerial(sv);
  
  Serial.print("sv="); Serial.print(sv);
  
  Serial.print("\n");
   
  int k = Serial.write(sv);

  Serial.print("k=");Serial.print(k);

  switch (k) {
  case 1:  //Serial.print("Kanuvai");
           source =  String("Kanuvai"); 
            break;
  case 2:  //Serial.print("KNG Pudur");
            source =  String("KNG Pudur");
            break;

default: 
    Serial.print("Enter a correct value");
   break;
    

  }
 
  Serial.println("Source");
  Serial.println(source);


}



/*
  Read input serial
 */
int readSerial(char result[])
{
  int i = 0;
  while(1)
  {
    while (Serial.available() > 0)
    {
      char inChar = Serial.read();
      if (inChar == '\n')
      {
        result[i] = '\0';
        Serial.flush();
        return 0;
      }
      if(inChar!='\r')
      {
        result[i] = inChar;
        i++;
      }
    }
  }
}

Result :

WHEN I GAVE 1 :
sv=1
1k=1Source
Kanuvai

WHEN I GAVE 1 :
 sv=2
2k=1Source
Kanuvai

"K" value is not updated .. Why is this not updates its values

Calling Serial.flush() will lose input - you really don't want to do this!

MarkT:
Calling Serial.flush() will lose input - you really don't want to do this!

Since version 1.0 Serial.flush() only affects output.

To clear/flush the input buffer, something like this is needed:

while( Serial.read() != -1 );

What is this line supposed to do ?

int k = Serial.write(sv);

...R

What is this line supposed to do ?

It stores, in k, the number of values written to the serial port. Useless information, in my opinion, but I'm sure OP has a good reason for doing that and failing to explain why it is a good idea.

PaulS:

What is this line supposed to do ?

It stores, in k, the number of values written to the serial port. Useless information, in my opinion, but I'm sure OP has a good reason for doing that and failing to explain why it is a good idea.

I had rather hoped you might guess that I know the answer and that I had posed it specially for the OP.

Now you have spoiled it all Boo Hoo Boo Hoo spoilsport :frowning:

...R