Search code examples
c#.netloopsconsole.readline

C#, Skipping Console.ReadLine(); Console.Read(); while in loop


If I run my code and insert correct value first time program works fine and does its job, but if I input wrong path and allow for loop to spin second time it skips path=Console.ReadLine(); but it does not skip j = (char)Console.Read(); same thing persist through out the remaining code.

do
{
    Console.WriteLine("Insert path:");
    path = Console.ReadLine();

    temp1 = CheckPath(path); //checks if inserted value is legit
    if (temp1 == false) 
    { 
        Console.WriteLine("\nDo you want to skip this step(by default directory will be set to Desktop)? Y/N ");
        j = (char)Console.Read(); 
        if (j.Equals('Y') || j.Equals('y')) 
        {
            path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); 
            temp1 = true; 
        }
    }
    //User inputs y/Y loop will end and exit with either path chosen by user or with desktop path
} while (!temp1);

path = Console.ReadLine(); is being skipped if user fails to insert correct path. Been looking for the solution since yesterday and I have failed to find identical problem on the web. Link to full code: Code.


Solution

  • The call isn't being skipped - the problem is that Console.Read() will only return after the user has hit return - although it will only consume the first character it reads. So suppose that (when prompted about skipping) the user enters:

    Nfoo
    

    and then hits return... the value of path in the next iteration will be foo.

    The simplest fix is probably to convert your Console.Read() call into Console.ReadLine() and just handle the situation where the user types more than one character.