Question

My code asks the user to enter a letter (convert string to char), but when pressing the Enter key as an input the code crashes.

I failed to put any conditions to send an error message to the user to not press the Enter key at the input and enter only letters.

Here is the part I'm struggling with :

public static char GetLetter(string prompt)
{
    char result;

    Console.Write("\n\t" + prompt + ":  ");
    result = Convert.ToChar(Console.ReadLine());

    if(result == '!' || result == '@' || result == '#'  || result == '$' || result == '%'  )
    // we can keep going with all the unwanted characters and numbers 
    {
        Console.WriteLine("\n\t NO MATCH ! \n\t ,please try again using letters only , ");
        result = GetLetter(prompt);
        return result;
    }

    return result;
}
Was it helpful?

Solution

You are getting an error when you enter because you get an empty string, so you can't convert it to char.

I would offer you to do that:

char result;
string input = Console.ReadLine();

if (char.TryParse(input, out result))
{
    //The input is a char - write your code here.
}

//The input is not a char.

OTHER TIPS

You can use Console.ReadKey() function to read the character as below:

public static char GetLetter(string prompt)
{
    char result;

    Console.Write("\n\t" + prompt + ":  ");
    result = Console.ReadKey().KeyChar;

    if (result == '!' || result == '@' || result == '#' || result == '$' || result == '%')
    // we can keep going with all the unwanted characters and numbers 
    {
        Console.WriteLine("\n\t NO MATCH ! \n\t ,please try again using letters only , ");
        result = GetLetter(prompt);
        return result;
    }

    return result;
}

Console.ReadLine() will return a string, not a char, use Console.Read instead. Check the details from MSDN

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top