Problems with console output in C #

I have lte problem on Console.WriteLine(). I have a while (true) loop that checks the data if it exists, and this will check the data 3 times. And inside my loop, I have this message:

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

Here is 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;

}

Assume no data was found.

My current output is as follows:

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

But the correct result that should have been achieved should look like this:

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

I would only show in one line.

Edit:

I forgot: in addition to my problem, I want to add "Not Found" and "Found".

Here's an example Output:

  • if the data found at the output of the first cycle is as follows.

    Checking data 1 ... Found!

  • , , .

    1... 2... !

  • , , .

    1... 2... 3... !

  1. 1... 2... 3... !
+5
8

Console.Write , , . , . -

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");
+8

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

+4

" " while. , :

Console.Write("Checking data ")
int ctr = 0;
while(true) {

    ctr += 1;

    Console.Write(string.format("{0}...",ctr))

    if (File.Exist(fileName)) break;

    if (ctr > 3) break;

}
+1

( , ) :

public static void Main(string[] args)
{
    int ctr = 0;
    string fileName = args[0];
    string result = "Checking data ";
    do
    {
        ctr += 1;
        result += ctr.ToString() + "...";
    }
    while(!File.Exists(fileName) && ctr <= 3);
    Console.WriteLine(result);
}
+1
public static void Main(string[] args)
{
    int retries = 0;
    bool success = false;
    int maxRetries = 3;
    string fileName = args[0];

    Console.Write("Checking data ");

    while(!success && retries++ < maxRetries)
    {
        Console.Write("{0}...", retries);
        success = File.Exists(fileName);
    }
    Console.WriteLine(" {0}Found!", (success ? "" : "Not ") );
}
+1

Use Console.Write()to not add a new line.

To prevent Data Verification printing more than once, take it out of the loop.

0
source

You have to use

Console.Write()
0
source

Try this code:

 int ctr = 0;
 string result = "Checking data ";
 while(true) {

     ctr += 1;

     result += ctr.ToString() + "...";

     if(File.Exist(fileName))
     {
         result += "Found";
         break;
     }

     if(ctr > 3)
     {
         result += "Not Found";
         break;
     }
 }
 Console.WriteLine(result);
-1
source

All Articles