Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with console output in C#

Tags:

c#

I have a litte problem on Console.WriteLine(). I have my while(true) loop that would check the data if exist and it would allow checking the data 3 times. And inside my loop I have this message:

Console.WriteLine(string.format("Checking data {0}",ctr));

Here's my sample code below:

int ctr = 0;

while(true)
{
  ctr += 1;

  Console.WriteLine(string.format("Checking data {0}...",ctr))  

  if(File.Exist(fileName)) 
     break;

  if(ctr > 3)
     break;

}

Let's assume that data was not found.

My current output show like this:

Checking data 1...
Checking data 2...
Checking data 3...

But the correct output that I should want to achieve should looks like this:

Checking data 1...2...3...

I would show only in one line.

Edit:

I forgot: In addition to my problem I want to append "Not Found" and "Found".

Here's the sample Output:

  1. if data found on the First loop output looks like this.

    Checking data 1... Found!

  2. if data found on the Second loop output looks like this.

    Checking data 1...2...Found!

  3. if data found on the Third loop output looks like this.

    Checking data 1...2...3...Found!

AND If data not found

  1. Checking data 1...2...3... Not Found!
like image 747
xxx_zzzz Avatar asked Feb 25 '10 06:02

xxx_zzzz


1 Answers

Use Console.Write instead if you don't want the line break. You also need to move the text out of the loop to avoid repeating it. Something like

Console.WriteLine("Checking data");
int ctr = 0;
bool found = false; 

while (ctr++ < 3 && !found) {
   Console.Write(" {0}...", ctr);
   if (File.Exists(fileName)) found = true;
}
Console.WriteLine(found ? "Found" : "Not found");
like image 125
Brian Rasmussen Avatar answered Oct 24 '22 11:10

Brian Rasmussen