Search code examples
c#charconsole.readlineconsole.readkey

In C# I am taking a char input and then I output something. But after input control is not waiting for enter and straightaway giving output


I have the following code:

using System;

namespace MyApp {
class KeyBoardInputTest {
    static void Main() {
        Console.Write("Enter a character >\t");
        char ch = (char)Console.Read();
        Console.WriteLine("");

        if(Char.IsLetter(ch)) {
            if(Char.IsUpper(ch))
                Console.WriteLine("You have entered an upper case character");
            else
                Console.WriteLine("You have entered a lower case character");
        }
        else if(Char.IsNumber(ch))
            Console.WriteLine("You have entered a numeric character");
        else
            Console.WriteLine("You have entered a non alpha-numeric character");
        Console.Read();
    }
}
} 

After taking an input such as a it is straightaway showing result without waiting for me to press Enter

Using Console.ReadLine() gives the error -

error CS0030: Cannot convert type 'string' to 'char'

Using Console.ReadKey() gives the error -

error CS0030: Cannot convert type 'System.ConsoleKeyInfo' to 'char'

Solution

  • For example try-parse:

    Console.Write("Enter a character >\t");
    char ch;
    char.TryParse(Console.ReadLine(), out ch);
    Console.WriteLine();
    

    You will get the null character '\0' if the user types too many characters, or no characters, before Enter. Alternatively, you can pick up the return value of TryParse, a boolean telling whether the parsing succeeded.