1

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?

Boyan Kushlev
  • 1,043
  • 1
  • 18
  • 35
  • 2
    Have you seen this: http://stackoverflow.com/questions/6825943/difference-between-console-read-and-console-readline ? – David Tansey Nov 02 '13 at 23:26
  • yes I have, but it doesn't matter if I use Read or ReadLine... It's still the same problem. I tried to use ReadLine and parse the value to double, but then it gives me an error message in the console itself... – Boyan Kushlev Nov 02 '13 at 23:31
  • please post that error message – UnholySheep Nov 02 '13 at 23:31

3 Answers3

1

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());
Community
  • 1
  • 1
  • 1
    It didn't work the first time, but it turned out that when I input a float-point value, I should use a comma, and not a decimal point. In other words, if I input 2.56 it shows me an error message, but when I input 2,56 everything works just fine! Thanks! – Boyan Kushlev Nov 02 '13 at 23:39
0

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);
geedubb
  • 4,048
  • 4
  • 27
  • 38
0

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,

AuthorProxy
  • 7,946
  • 3
  • 27
  • 40