Why Doesn't Read() work as Expected? - c#

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?**
}
}
}

//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

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

Related

Make user press specific key to progress in program

I am currently working on a little lottery console game and wanted to add a "Working" mechanic. I created a new method and want to add multiple tasks where you have to press a specific key like the space bar for example multiple times. So something like this (but actually working):
static void Work()
{
Console.WriteLine("Task 1 - Send analysis to boss");
Console.WriteLine("Press the spacebar 3 times");
Console.ReadKey(spacebar);
Console.ReadKey(spacebar);
Console.ReadKey(spacebar);
Console.WriteLine("Task finished - Good job!");
Console.ReadKey();
}
The Console.ReadKey() method returns a ConsoleKeyInfo structure which gives you all the information you need on which key and modifiers were pressed. You can use this data to filter the input:
void WaitForKey(ConsoleKey key, ConsoleModifiers modifiers = default)
{
while (true)
{
// Get a keypress, do not echo to console
var keyInfo = Console.ReadKey(true);
if (keyInfo.Key == key && keyInfo.Modifiers == modifiers)
return;
}
}
In your use case you'd call that like this:
WaitForKey(ConsoleKey.SpaceBar);
Or you could add a WaitForSpace method that specifically checks for ConsoleKey.SpaceBar with no modifiers.
For more complex keyboard interactions like menus and general input processing you'll want something a bit more capable, but the basic concept is the same: use Console.ReadKey(true) to get input (without displaying the pressed key), check the resultant ConsoleKeyInfo record to determine what was pressed, etc. But for the simple case of waiting for a specific key to be pressed that will do the trick.

ReadKey getting characters pressed before a thread timeout has ended

i'm attempting my first c# console-based game. I created a centered credits intro with a "press any key to continue..." printed at the end. I used Console.ReadKey() to emulate a pause as it waits for user input. The problem is that you can 'stack' inputs, there is probably a better term but essentially, while the console is in a timeout the key inputs are still read and are queued until the timeout ends.
for example;
//10 second wait
//this is where I would press a key
Thread.Sleep(10000);
char x = Console.ReadKey().KeyChar;
//x will be equal to whatever key I pressed before the timeout
this is not the functionality i'm after. does anyone have a solution to this e.g; not use Thread.Sleep() or Console.ReadKey()
If you still do not understand the question, press a key while the Thread.Sleep() is still in effect and the readkey, after the time is up will print that character. does anyone know how to stop the reading of the key?
If you would like actual project code, just ask. Although I see it as irrelevant for this question.
If you want to clear the buffer before waiting for a key, you can call Console.ReadKey(true) in a loop for as long as there is a KeyAvailable. Passing true to the method specifies that the key should be intercepted and not be output to the console window.
For example:
Thread.Sleep(TimeSpan.FromSeconds(10));
// Clear buffer by "throwing away" any keys that were pressed while we were sleeping
while(Console.KeyAvailable) Console.ReadKey(true);
char x = Console.ReadKey().KeyChar;

C# - Passively checking for key press

I am not using windows forms so this is not a duplicate of Capture keystroke without focus in console. Please remove the duplicate label or direct me somewhere else
So have been away from C# for a long time and trying to get back into it. I am messing with a small console app that requires inputting text from the user. The whole program works fine but now I want to add a check to see if escape is ever pressed.
I originally used ReadKey, but that just checks the current key which has two problems.
1. it uses the key pressed, so strings are missing a character (the one which was checked)
2. it is only in the moment. I want it to be passively waiting until its pressed
What would be the best way to do this?
ex:
I type the string "Hello World!"
If I press the desired key(lets say escape) at any time, I want it to react. Otherwise the string should be entered like normal
edit
example of made up dictionary program (yes, I know there is already a class for this)
while (Console.ReadKey().Key != ConsoleKey.Escape)
{
string entry = Console.ReadLine();
if (!entry.Contains(","))
{
...
}
else
{
...
}
}
Thank you all very much for your time.
Not sure what you're getting at but you can use this to detect if the Escape key was pressed.
if (Console.KeyAvailable)
if (Console.ReadKey(true).Key == ConsoleKey.Escape)
{
// Do something
}
}
Or alternatively use a loop that breaks when Escape is entered:
var x = Console.ReadKey();
while (x.Key.ToString() != "Escape")
x = Console.ReadKey();

C# Console Program issues

I need help in understanding what may be wrong with this simple C# console app program. What I want to do, is perform various arithmetic operations via classes. Here is the program.
static void Main(string[] args)
{
Console.Clear();
Arithmetic a1 = new Arithmetic();
Console.Write("\nEnter the value for first variable\n");
a1.obj1 = Console.Read();
Console.Write("\nEnter the value for the second variable\n");
a1.obj2 = Console.Read();
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
Apparantley, the program builds and compiles ok, but on the run time it takes the value of the first integer, and without taking the value of the next integer, it writes the last line on the display (Press any key to exit)
Console.Read() reads a single character from standard input, and returns its ASCII value.
If you press two keys, each Console.Read() call will return one of them
You probably want ReadLine(), which reads an entire line of text (which you will then want to parse into an int).

C# Console Application - Calling Main method or Class?

I have exercise/drill/homework assignment to create a C# program to compute the value of a number raised to the power of a second number. Read the two numbers from the keyboard.
Ask the user for an integer.
Print the integer back to the screen and asked if it is correct.
If the integer is correct, continue on.
If the integer is incorrect, start program from the beginning.
I have two questions:
Can and how do I programmatically clear the console window?
Start over, do I call the Main method or the Class?
How do I do either, calling the main method or the class?
Here's what I've written so far:
using System;
using System.Text;
namespace CalcPowerOfNums
{
class Program
{
//Declaring the two main string variables to be used in our calculation.
string firstUserString;
string secondUserString;
static void Main(string[] args)
{
//Ask the user for the first number.
Console.WriteLine("Enter your first number and press the Enter/Return key");
string firstUserString = Console.ReadLine();
//Make sure this number is correct.
Console.WriteLine("You want to find the power of {0}?\n" , firstUserString);
//Declaring, Initializing string variables for user answer.
string firstAnswer = "";
//Make user confirm or deny their choice.
Console.WriteLine("Press the lowercase letter y for yes");
Console.WriteLine("Press the lowercase letter n for no");
Console.ReadKey();
//If user answer is yes, move on… It user answer is no, start program over.
do
{
if (firstAnswer == "y")
continue;
if (firstAnswer == "n")
}
Looking at the Console class, you will find a Clear method that will clear the console screen. As to calling Main, that will be called automatically by default in a console project as long as you have declared it. You can have a look in your project properties at the Startup Object setting.
When you say "start the program over" I am assuming you mean clear the window and ask for the input again, not reload the entire process.
You can use Console.Clear() to clear the console window. The main method is called automatically from Program.cs. Just place your main code in a while loop and loop until you get the desired input. If you don't get the desired input, just issue a Console.Clear() and ask again until you do.
I have two questions: Can and how do I programmatically clear the console window?
Yes, by calling Console.Clear.
Do I call the Main method or the Class?
You cannot invoke a class, and you should never call main directly. Just put a do/while loop around it with 'is correct' as the condition:
do {
...all regular code...
} while(firstAnswer == 'y');
What about:
Console.Clear();
?
you should make functions for this. Put the enter name part in a function then call this function at the start of the Main function and in the if statements.

Categories

Resources