Question

Here's a simple example to illustrate the problem:

class Test
{
    static void PrintName()
    {
        Console.Out.Write("Enter your name: "); 
        string name = Console.In.ReadLine();
        Console.WriteLine(name);

        Console.Out.Write("\nEnter R to restart: ");
        char r = Convert.ToChar(Console.In.Read());

        if (r.ToString().Equals("r", StringComparison.OrdinalIgnoreCase))
            PrintName();
        else
            Environment.Exit(0);

    }

    static void Main(string[] args)
    {
        PrintName();
    }
}

Basically, PrintName asks to restart itself. On the first run it accepts the user input and displays the name fine. When asked to repeat the procedure, it just displays the prompt and asks if you want to restart. It skips past waiting for input or displaying output.

UPDATE: Output is:

Enter your name: Naven
Naven

Enter R to restart: r
Enter your name:

Enter R to restart: r
Enter your name:

Enter R to restart:
Was it helpful?

Solution

It is an expected behavior. ReadLine will read characters until it finds '\n' in the other hand Read will not read '\n' so when you read the command r you will have a '\n' in your buffer and so you arrive in ReadLine and pass directly.

so you have to clean the buffer a simple ReadLine will do just that.

class Test
{
    static void PrintName()
    {
        Console.Out.Write("Enter your name: ");
        string name = Console.In.ReadLine();
        Console.WriteLine(name);

        Console.Out.Write("\nEnter R to restart: ");
        char r = Convert.ToChar(Console.In.Read());

        if (r.ToString().Equals("r", StringComparison.OrdinalIgnoreCase))
        {
            Console.In.ReadLine();
            PrintName();
        }
        else
            Environment.Exit(0);

    }

    static void Main(string[] args)
    {
        PrintName();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top