Question

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?

Était-ce utile?

La 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());

Autres conseils

It assumes that you enter already \n as a second input. If you enter 2 numbers on the first Read method. Than it tooks 1 number in first read and second number on the second automatically. Just replace with ReadLine() if you want to achieve noraml behaviour,

Try Console.ReadLine() instead. Console.Read only reads a single character

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

Or with TryParse:

   Console.WriteLine("Enter first number: ");
   double num1, num2;
   double.TryParse(Console.ReadLine(), out num1); // double.TryParse() method also returns a bool, so you could flag an error to the user here
   Console.WriteLine("Enter second number: ");
   double.TryParse(Console.ReadLine(), out num2);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top