this is a beginner type question, and I am sorry for my poor English.
here is the program:
using System;
public class BoolTest
{
static void Main()
{
Console.Write("Enter a character: ");
char c = (char)Console.Read();
if (Char.IsLetter(c))
{
if (Char.IsLower(c))
{
Console.WriteLine("The character is lowercase.");
}
else
{
Console.WriteLine("The character is uppercase.");
}
}
else
{
Console.WriteLine("Not an alphabetic character.");
}
}
}
MSDN output is:
Enter a character: X
The character is uppercase.
Additional sample runs might look as follow:
Enter a character: x
The character is lowercase.
Enter a character: 2
The character is not an alphabetic character.
my output doesn’t say anything for this version of code. If I added a while(1==1) line before the if statement, I take three line output like:
Enter a character: X
The character is uppercase.
The character is not an alphabetic character.
The character is not an alphabetic character.
Enter a character: x
The character is lowercase.
The character is not an alphabetic character.
The character is not an alphabetic character.
Enter a character: 2
The character is not an alphabetic character.
The character is not an alphabetic character.
The character is not an alphabetic character.
I tried Console.ReadLine() end of the else statement but does not work. Also I tested comment the else blocks with while (1==1), I get only 1 output line..
I am wondering why the output is including 3 lines for me for the same sample code ?
My first answer was wrong –
Console.Read()blocks. You probably just missed the output when running the program from Visual Studio because the window closes immediately. Just appendConsole.ReadLine();twice at the end of the program to keep the window open. The firstConsole.ReadLine();will consume the return you pressed after the character, the second one will wait until you press return again and therefore keep the window open.Or slightly modify the program to use
Console.ReadKey()– useand add a single
Console.ReadLine();at the end of the program.Console.ReadKey()will not block until you hit return and therefore there is no need to consume the new line with a secondConsole.ReadLine();.Original answer
Console.Read()does not block and will immediately return-1if no character is available. You could just insertright before
to wait until a character is available.