Question

I'm learning C# (VS 2012 Professional) and in the following example, the console window isn't staying open even though the Console.ReadLine() method is the last instruction in the code block:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace testing
{
    class Program
    {
    static void Main(string[] args)
    {

        // fahrenheit conversion example
        Console.Write("Enter temp in fahrenheit: ");
        double fahrenheit = Console.Read();
        double celsius = (fahrenheit - 32.0) * (5.0 / 9.0);
        Console.WriteLine("Celsius is: " + celsius);
        Console.ReadLine();

    }

    }
}

Is there an intricacy I am overlooking in the implementation of the Console.ReadLine() method or perhaps a conflicting piece of code in the code block?

Was it helpful?

Solution

Probably you type the value for the fahrenheit variable and then press Return (Enter). This will get the value in the Read call and the Enter in the ReadLine.

Change to

Console.Write("Enter temp in fahrenheit: ");
double fahrenheit;
string userInput = Console.ReadLine();
if(double.TryParse(userInput, out fahrenheit))
{
    double celsius = (fahrenheit - 32.0) * (5.0 / 9.0);
    Console.WriteLine("Celsius is: " + celsius);
}
else
{
    Console.WriteLine("Non a valid double value");
}
Console.ReadLine();

Also, the Console.ReadLine, unlike the Console.Read, returns a string and thus you need to parse and convert to a double before trying to use it. This could be done with double.TryParse that will return false when the user doesn't type a valid numeric double

Another drawback for Console.Read is that you need to call it in a loop to read all characters typed by the user till the Enter. If you try to convert 12.8 you need a completely different code to go with Console.Read. (Look at the MSDN example in the link above)

OTHER TIPS

Console.Read() "Reads the next character from the standard input stream". This includes the Enter key. It returns an integer so, for Enter, would return 13.

Console.ReadLine() "Reads the next line of characters from the standard input stream". This includes the Enter key (the newline character) but this character is discarded. it returns a string.

Console.ReadKey() "Obtains the next character or function key pressed by the user". That is, it ignores whatever is left in the input stream and waits for the next key-press.

So you might use Read() within a loop to read individual characters, stopping when a certain character is read, or use ReadLine() to read, and then parse, the complete line entered by the user. But using both Read() and ReadLine() in the same code can be problematic.

Just press Ctrl+F5 to run the code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top