Search code examples
c#consolefflush

Clear the current line, as with fflush(stdout) in C


I have a very long for loop, which prints out many lines of information. I would like to keep it to just one line that overwrites previous lines. I tried Console.out.flush() but it does not seem to work.


Solution

  • Use

    Console.SetCursorPosition
    

    to get where the Cursor is at use

    Console.CursorLeft
    Console.CursorTop
    

    Example

    int i = 0;
    
    Console.WriteLine("Numbers will count below this line");
    
    int cLeft = Console.CursorLeft;
    int cTop = Console.CursorTop;
    
    while (true)
    {
        Console.SetCursorPosition(cLeft, cTop);
        Console.WriteLine(i);
        i++;
    }