MatMis
MatMis

Reputation: 319

Why is the beginning of the string overwritten instead of pasting it to the end?

I'm building a temperature logger.

screenshot: https://i.sstatic.net/jQ5s7.jpg;

while (true)
{
      string line = myport.ReadLine(); // line = *"T: 18.40"*

      if (line.StartsWith("T"))
      {
          line = line.Substring(3) + "°C";
          Console.WriteLine(line);
          // output is *"°C.40"* instead of *"T: 18.40°C"*                   
      }
}

Upvotes: 1

Views: 104

Answers (2)

Henk Holterman
Henk Holterman

Reputation: 273244

Most likely your input line is ending with "\r", the output on the console screen is not a good representation of what the line actually is.

Console.WriteLine("18.40\r°C")

will look on the screen like

°C.40

one solution is to clean the input from myport (a SerialPort I guesss?)

string line = myport.ReadLine(); // line = "T: 18.40\r"
line = line.Trim();              // remove all leading/trailing whitespace

But it shouldn't have happened. The ReadLine() should have removed the line ending. Somehow your myport.NewLine property is set to "\n" while it should be "\r\n".

Upvotes: 5

Mario Dekena
Mario Dekena

Reputation: 843

The line is most likely not what you expect it to be. Try this, it might be more stable.

line = line.Split(' ').Last() + "°C";

Upvotes: -1

Related Questions