0

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'
puregeek
  • 175
  • 3
  • 9

4 Answers4

1

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.

Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181
  • Thanks, it works. Can you please explain the meaning of "char.TryParse(Console.ReadLine(), out ch);"? I am new to C#. – puregeek Dec 19 '17 at 20:00
  • 1
    @puregeek The method `Console.ReadLine()` returns a `string` which is like a whole text consisting of many characters. You could have used that directly, as in `string st = Console.WriteLine();`, but then you would modify the rest of your program. Instead I used the `TryParse` method which checks whether it is possible to "see" the `string` as a `char`. When it succeeds, it puts its result in the `out` parameter. When it fails, it does not blow up, it just puts the zero character `'\0'` into that `out` variable. – Jeppe Stig Nielsen Dec 19 '17 at 20:04
  • That means if for example, I input "ab" instead of "a" and then press enter then '\0' gets stored in out? @JeppeStigNielsen – puregeek Dec 19 '17 at 20:12
  • 1
    @puregeek Yes! We get `char.TryParse("ab", out ch)`, and it will not parse, and you get `'\0'`. An alternative, with `using System.Linq;` added at the top, would be just `char ch = Console.ReadLine().FirstOrDefault();` which takes the first character of the string, and only resorts to `'\0'` in the case where the string has no characters (the empty string, when user presses Enter immediately). – Jeppe Stig Nielsen Dec 19 '17 at 20:23
  • As a side note, it is a request, can you please say, can we assign octal literal to byte? @JeppeStigNielsen – puregeek Dec 19 '17 at 20:34
0

Consider pivoting your code to accept input as arguments and convert the input to a char using the System class Convert.ToChar()

using System;

namespace MyApp {

class KeyBoardInputTest {
static void Main(string [] args) {    // This line has been changed
    Console.Write("Enter a character >\t");
    char ch = Convert.ToChar(args[0])   // This line has been changed
    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();
}
}
} 
objectively C
  • 960
  • 9
  • 25
  • But it will not wait for input, or get input, from the console. Taking parameters from the command line is something else. Also, `Convert.ToChar` will blow up if the string is not length one. – Jeppe Stig Nielsen Dec 19 '17 at 19:51
  • Giving error (5,31): error CS1552: Array type specifier, [], must appear before parameter name and (7,37): error CS1002: ; expected – puregeek Dec 19 '17 at 19:56
0

Just grab the first character of the String which Console.ReadLine() returns

namespace MyApp {
class KeyBoardInputTest {
    static void Main() {
        Console.Write("Enter a character >\t");
        char ch = Console.ReadLine()[0];
        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();
    }
}
} 

Keep in mind this removes any additional characters the user may have entered. It will also cause an IndexOutOfRangeException if you the user does not enter any information.

ctg
  • 1
  • 1
0

For a Dirtier, but very flexible code, you can use Try-Catch to get the input.

Make sure that you initialize the variable with something like: ch = 'c';

Then use this piece of code:

    try()          //You can get the try-catch code snippet by typing 'try' and hit enter or tab
    {
       ch = Convert.ToChar(Console.ReadLine());
    }
    catch(Exception e)
    {
       Console.WriteLine("Enter a Valid Character");  //You can also recurse your function after this
    }

This method is a bit Unclean, but you still can do a lot more in it as compared to other ways. (Like calling a function inside 'catch' or 'try').