Search code examples
c#console.readline

Console.Read() doesn't allow me to input anything the second time


I'm solving a problem about comparing two floating-point numbers and I want to let the user input desired values. So I wrote the following code:

    Console.WriteLine("Enter first number: ");
    double num1 = Console.Read();
    Console.WriteLine("Enter second number: ");
    double num2 = Console.Read();

Unfortunately, I can only input the first number. After the console outputs "Enter first number: " and I enter some number, it simply skips to the end and doesn't let me enter the second number... Any thoughts on that?


Solution

  • That is the default behaviour of Console.Read(). From an answer on Difference between Console.Read() and Console.ReadLine()?

    Console.Read() basically reads a character so if you are on a console and you press a key then the console will close. [...]

    You should use Console.ReadLine(); instead.

    Console.WriteLine("Enter first number: ");
    double num1 = double.Parse(Console.ReadLine());
    Console.WriteLine("Enter second number: ");
    double num2 = double.Parse(Console.ReadLine());