Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Console.Clear be used to only clear a line instead of whole console?

Tags:

c#

While working on a question/answer program for school, it occurred to me that I can use Console.Clear() to wipe out everything on the screen. I wonder if I can use Console.Readline(valueOne), then output only the answer without the question. If I only asked one question, the Console.Clear works.

I have several questions with values not references, to erase if possible. I want to leave out the questions and only display several answers. I think if I store the answers, I could use Console.Clear() then just Console.WriteLine() with three variables. I could do something like this:

Console.WriteLine("Value 1 is: {0:c}" + "Value 2 is: {1:c}" + "Value 3 is: {2:c}, valueOne, valueTwo, valueThree). 

The problem is easier with references because the values are stored and retrieved. If I simply use methods to pass by value and output the value, main() will not have a reference to those values to clear and output again. That's why I wonder if I can just ask a question, then erase the line and output only the answer (or answers).

I am just trying to understand the possibilities and not trying to setup a program. I like to know the abilities of outputting a value from reference and by value without extra output questions.

like image 520
bad boy Avatar asked Jan 20 '12 19:01

bad boy


People also ask

What does console Clear () do?

Clears the console buffer and corresponding console window of display information.


2 Answers

Description

You can use the Console.SetCursorPosition function to go to a specific line number. Then you can use this function to clear the line:

public static void ClearCurrentConsoleLine() {     int currentLineCursor = Console.CursorTop;     Console.SetCursorPosition(0, Console.CursorTop);     Console.Write(new string(' ', Console.WindowWidth));      Console.SetCursorPosition(0, currentLineCursor); } 

Sample

Console.WriteLine("Test"); Console.SetCursorPosition(0, Console.CursorTop - 1); ClearCurrentConsoleLine(); 

More Information

  • Console.SetCursorPosition Method
like image 165
dknaack Avatar answered Oct 13 '22 05:10

dknaack


A simpler and imho better solution is:

Console.Write("\r" + new string(' ', Console.WindowWidth) + "\r"); 

It uses the carriage return to go to the beginning of the line, then prints as many spaces as the console is width and returns to the beginning of the line again, so you can print your own test afterwards.

like image 31
hellow Avatar answered Oct 13 '22 04:10

hellow