RShome
RShome

Reputation: 537

Console.ReadLine is missing an input when written in a While Loop

I have two input lines which accept user input but when writing within a While Loop, the first user input is ignored

I have tried this on C# whout the while loop and both lines of user input are accepted.

First console window when executing below code without a While Loop Without While Loop

Second console window when encased in a While Loop (n=both user inputs are on one line and the number of solders is empty. enter image description here

    public static void Main(string[] args)
    {
        String numSoldiers; //number of soldiers
        String arms; // power
        int Q = 1;

        while (Q <= 4)
        {
            Console.Write("Enter Total Number of Soldiers: ");
            numSoldiers = Console.ReadLine();

            Console.Write("Enter number of arms: ");
            arms = Console.ReadLine();

            Console.WriteLine("There are " + numSoldiers + " soldiers and " + arms + " arms");

            Console.Read();

            Q++;
        }
    }
}

Upvotes: 0

Views: 722

Answers (2)

Sweeper
Sweeper

Reputation: 271410

I suppose you wanted to allow the user to press enter before the loop continues its next iteration, right? That's why you called Console.Read() near the end of the loop.

However, Console.Read only reads 1 character, but when you press enter, there are actually 2 characters being entered (at least on Windows), and they are \r and \n. Console.Read reads the \r, leaving \n unread.

In the next iteration of the loop, the first call to Console.ReadLine reads the \n, which is an empty line, so it returns an empty string. Note that it didn't wait for the user to enter anything, because it sees that there is still some characters unread.

To fix this, you can call ReadKey instead of Read.

Console.ReadKey();

Upvotes: 4

Theodor Zoulias
Theodor Zoulias

Reputation: 43495

Try replacing:

Console.Read();

...with:

Console.WriteLine();
Console.ReadKey(true);

Upvotes: 2

Related Questions