Home >Backend Development >C++ >How Can I Overwrite the Same Line in a C# Windows Console Application?

How Can I Overwrite the Same Line in a C# Windows Console Application?

Barbara Streisand
Barbara StreisandOriginal
2025-01-21 10:36:11993browse

How Can I Overwrite the Same Line in a C# Windows Console Application?

Overwrite same line in C# Windows console application

Many C# Windows console application developers want to update the same row in the console window without creating a new row. For example, a developer might want to show the progress of a process by displaying a percentage on the same line.

Is this possible?

You can overwrite the current line in a C# console application by using the "r" escape sequence. The "r" carriage return moves the cursor to the beginning of the line, allowing you to rewrite it.

Sample code:

<code class="language-csharp">for (int i = 0; i < 100; i++)
{
    Console.Write("\r{0}% ", i);
    Thread.Sleep(100);
}</code>

Instructions:

  • The loop iterates from 0 to 99.
  • Within the loop, "r" is written to the console to move the cursor to the beginning of the current line.
  • Then write the current percentage (i) in the format of "{0}%".

Note:

  • Use a space or other character after the percentage to erase any previous text on the line.
  • Use Write() instead of WriteLine() to avoid adding newlines.

The above is the detailed content of How Can I Overwrite the Same Line in a C# Windows Console Application?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn