views:

113

answers:

2

I'm using Visual Studio 2008 for C#. I can't understand why this simple code does not work as expected. Any ideas? Thanks!

using System;

namespace TryRead
{
    class Program
    {
        static void Main()
        {
            int aNumber;
            Console.Write("Enter a single character: ");
            aNumber = Console.Read(); **//Program waits for [Enter] key. Why?**
            Console.WriteLine("The value of the character entered: " + aNumber);
            Console.Read(); **//Program does not wait for a key press. Why?**
        }
    }
}
+4  A: 

//Program waits for [Enter] key. Why?

The Read method blocks its return while you type input characters; it terminates when you press the Enter key. Pressing Enter appends a platform-dependent line termination sequence to your input (for example, Windows appends a carriage return-linefeed sequence).

//Program does not wait for a key press. Why?

Subsequent calls to the Read method retrieve your input one character at a time [without blocking]. After the final character is retrieved, Read blocks its return again and the cycle repeats.

http://msdn.microsoft.com/en-us/library/system.console.read.aspx

Robert Harvey
Thank you for your answer. For some reason, the book I'm using to learn C# (C# Programming from Problem Analysis to Program Design by Barbara Doyle) makes no mention of this behavior. Someone else suggested KeyAvailable. I think I'll have a look at that.
Jimmy
In other words, Read() is meant to loop over the characters entered *after* the Enter key has been pressed, not while the keys are being pressed.
Greg
Apparently I'm too much of a newbie to grasp KeyAvailable, and Help seems to indicate that ReadKey is referring to the Registry. I guess I'll just use ReadLine instead. I am surprisedf that this code does not seem to give the result the book indicated would occur. Any book suggestions for a greenhorn?
Jimmy
Have a look at ReadKey, rather than KeyAvailable: http://msdn.microsoft.com/en-us/library/471w8d85.aspx. The ReadKey method waits, that is, blocks on the thread issuing the ReadKey method, until a character or function key is pressed.
Robert Harvey
Thanks to everyone for the comments. I had a look at ReadKey. I think that may be what I'm looking for, but it is described as an attribute, and I haven't gotten to the section on attributes yet. I can get by with ReadLine for now.
Jimmy
ReadKey has attributes associated with it, but they're not relevant for your purposes. ReadKey is a method; just substitute it where you have Read() now.
Robert Harvey
+2  A: 

You need to use Console.ReadKey() instead of Console.Read().

dviljoen