Console.ReadLine() skips the first input character - c#

Console.WriteLine("You have not installed Microsoft SQL Server 2008 R2, do you want to install it now? (Y/N): ");
//var answerKey = Console.ReadKey();
//var answer = answerKey.Key;
var answer = Console.ReadLine();
Console.WriteLine("After key pressed.");
Console.WriteLine("Before checking the pressed key.");
//if(answer == ConsoleKey.N || answer != ConsoleKey.Y)
if (string.IsNullOrEmpty(answer) || string.IsNullOrEmpty(answer.Trim()) || string.Compare(answer.Trim(), "N", true) == 0)
{
Console.WriteLine("The installation can not proceed.");
Console.Read();
return;
}
I have tried to input these:
y -> it gives me an empty string,
y(whitespace+y) -> it gives me the "y"
I have checked other similar posts, but none of them solves my problem.
The ReadLine() still skips the 1st input character.
UPDATE Solved, see below.

Suggested change:
Console.Write("Enter some text: ");
String response = Console.ReadLine();
Console.WriteLine("You entered: " + response + ".");
Key points:
1) A string is probably the easiest type of console input to handle
2) Console input is line oriented - you must type "Enter" before the input becomes available to the program.

Thank you all for replying my post.
It's my bad that not taking consideration of the multi-thread feature in my code. I will try to explain where I was wrong in order to say thank you to all your replies.
BackgroundWorker worker = .....;
public static void Main(string[] args)
{
InitWorker();
Console.Read();
}
public static void InitWorker()
{
....
worker.RunWorkerAsync();
}
static void worker_DoWork(....)
{
.....this is where I wrote the code...
}
The problem was I started a sub-thread which runs asynchronously with the host thread. When the sub-thread ran to this line : var answer = Console.ReadLine();
the host thread ran to the Console.Read(); at the same time.
So what happened was it looked like I was inputting a character for var answer = Console.ReadLine();, but it actually fed to the Console.Read() which was running on the host thread and then it's the turn for the sub-thread to ReadLine(). When the sub-thread got the input from keyboard, the 1st inputted character had already been taken by the host thread and then the whole program finished and closed.
I hope my explanation is clear.

Basically you need to change Console.Read --> Console.ReadLine

Related

This code for tire pressure keep running off the screen

The code I have doesn't work with console.writeline
I'm not to use console.readline
[] tirePressure = new int [4];
string valueTestFail = "Get you tire check as soon as possible.";
Console.WriteLine("Let check your tires!\r\nPlease enter the pressure for the front right tire.");
string frontRightTire = Console.ReadLine();
while(!int.TryParse(frontRightTire, out tirePressure[0])){
Console.WriteLine(valueTestFail);
frontRightTire = Console.ReadLine();
} Console.WriteLine("Please Enter the pressure for the front left tire.");
string frontLeftTire = Console.ReadLine();
while(!int.TryParse(frontLeftTire, out tirePressure[1])){
Console.WriteLine(valueTestFail);
frontLeftTire = Console.ReadLine();
}
Console.WriteLine("Please Enter the pressure for your rear right tire.");
string rearRightTire = Console.ReadLine();
while(!int.TryParse(rearRightTire, out tirePressure[2])){
Console.WriteLine(valueTestFail);
rearRightTire = Console.ReadLine();
}
Console.WriteLine("Please enter the value of the rear left tire.");
string rearLeftTire = Console.ReadLine();
while(!int.TryParse(rearLeftTire, out tirePressure[3])){
Console.WriteLine(valueTestFail);
string rearLeftTire = Console.ReadLine();
}
if(tirePressure[0]==tirePressure[1] && tirePressure[2]==tirePressure[3]){
Console.WriteLine("The tires pass spec!");
}else{
Console.WriteLine("Get your tires checked out.");
}
The error code so long, the code just run the entire screen and I just want to console.writeline this code line
it sounds like you are trying to use a Windows .NET feature in Xamarin. I Googled "console writeline xamarin" and got some alternatives. Try System.Diagnostics.Debug.WriteLine(), for instance.
You might look at this URL, https://forums.xamarin.com/discussion/18387/equivalent-of-console-writeline, to see if the information there is able to help you out.
I've been using C# for over 10 years, I read through your C# code, and I don't see anything incorrect with it... if it's running on Windows. You might improve its style, but that's not what you're looking for, is it.

How to get a console to read through all conditions

I have a console application that asks the user to choose one of three options and to be able to open an inventory if desired. However, instead of checking to see if any of the other conditions are true are false, the console just reads the conditions linearly and waits till the first one has been satisfied. So for example, in the code below, it runs the first bit of text, presents the options, and then waits for the user to enter "inventory" without considering the other options. What's up? Why does this happen? and how do I get the console to run through and check whether or not all conditions have been satisfied?
Here's the code
using System;
using System.IO;
namespace Feed_de_monky
{
class Program
{
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Green;
string one = "";
string two = "";
string inventory = "inventory";
int storyint = 0;
TextReader input = Console.In;
TextWriter output = Console.Out;
int options = 0;
if (storyint == 0)
{
Console.WriteLine("You are in a dark Jungle. You look into the darkness of the trees and see the silhouette of a tiger standing in front of you down the way.");
Console.WriteLine("");
Console.WriteLine("turn and run");
Console.WriteLine("pounce on tiger");
Console.WriteLine("climb a tree.");
options++;
if (input.ReadLine() == inventory)
{
output.WriteLine(one);
output.WriteLine(two);
return;
}
else if(input.ReadLine() == "turn and run" && options == 1)
{
output.WriteLine("");
output.WriteLine("The tiger chases you through the darkness. You never had a chance.");
Console.Write("Press any key to continue...");
Console.ReadKey(true);
}
else if(input.ReadLine() == "pounce on tiger" && options == 1)
{
output.WriteLine("");
output.WriteLine("The tiger is caught by surprise. You overwhelm the beast and he dies of shock and surprise on the spot");
one = "tiger skin";
output.WriteLine("TIGER SKIN ADDED TO YOUR INVENTORY");
storyint++;
options++;
}
else if(input.ReadLine() == "climb a tree" && options == 1)
{
output.WriteLine("");
output.WriteLine("You climb the tree. But while you sit on the branches believing yourself to be safe, the tiger jumps through the air and bites your head clean off. You never had a chance.");
Console.Write("Press any key to continue...");
Console.ReadKey(true);
}
Console.Write("Press any key to continue...");
Console.ReadKey(true);
}
}
}
}
I think you might need to set
var inputLine = input.ReadLine();
And then do your logic on the variable inputLine.
As you have it now I believe it will call ReadLine more times than you are expecting. But if you just call .ReadLine() one time and assign it to a variable that should act better than calling it repeatedly.

How do I stop my C# console program from stopping when executing "console.readline();" twice

i'm really new to C# and i've been working on this really simple command line style program (that has custom commands and such). Now the commands work great but every time I allow the user to go back to enter another command or just anything it closes the program when I press enter. But only the second time I execute a command. I think this has something to do with console.WriteLine();
Here's my code (I've searched everywhere on how to fix this and nothing that i've found has worked)
using System;
namespace ConsoleProgram
{
class Program
{
private static string userEnteredCommand;
static void Main(string[] args)
{
Console.Title = "IAO Systems Service Console";
onCommandLineStart();
void onCommandLineStart()
{
Console.WriteLine("Copyright (C) 2018 IAO Corporation");
Console.WriteLine("IAO Systems Service Console (type 'sinfo' for more information.");
userEnteredCommand = Console.ReadLine();
}
void onCommandLineReturn()
{
userEnteredCommand = Console.ReadLine();
}
// Commands
if (userEnteredCommand == "sinfo")
{
Console.WriteLine(" ");
Console.WriteLine("Program information:");
Console.WriteLine("Created for IAO Corporation, by Zreddx");
Console.WriteLine("This program controls doors, gates and e.t.c within IAO Terratory.");
Console.WriteLine(" ");
Console.WriteLine("This program is protected by copyright, do not redistribute. ");
}
else
{
Console.WriteLine("That command does not exist, do 'programs' for a list of actions.");
}
onCommandLineReturn();
}
}
}
Console applications close when they get to the end of Main. It's exiting after the Console.ReadLine in onCommandLineReturn();.
Add a bool variable called keepLooping, set it to true, and wrap your code in a while(keepLooping) statement. Somewhere in your program flow, check for input like "quit" or "exit" and set the keepLooping variable to false.
Here's an example of it in a dotnetfiddle: https://dotnetfiddle.net/Jguj5k

How do I use if else statements in c#?

I'm from a python background and I'm finding it difficult to pick up the syntax in c#.
I'm trying to write code so that the program will continuously ask the user for input and it will echo it on the screen, but if the user input is 'exit' then it exits.
I tried
Console.WriteLine("Hello World!");
Console.Write("Enter some text: ");
string userinput = Console.ReadLine();
if (userinput == "exit")
{
Console.ReadKey();
}
else
{
Console.WriteLine(userinput);
But it doesn't achieve expected results
An if statement only executes once.
Since you're looking to take some action repeatedly, a do/while construct is more along the lines of what you need.
Something like this should at least get you started in the right direction:
string userinput;
do
{
Console.Write("Enter some text: ");
userinput = Console.ReadLine();
Console.WriteLine(userinput);
}
while (userinput != "exit");

Console terminates after Console.Read(), even with Console.ReadLine() at the end

The following code asks for your name and surname.
class Program
{
static void Main(string[] args)
{
Console.Write("Enter your name: ");
string s = Console.ReadLine();
Console.WriteLine("Your name: " + s);
Console.Write("Enter your surname: ");
int r = Console.Read();
Console.WriteLine("Your surname: " + r);
Console.ReadLine();
}
}
After entering the name, the program successfully displays your input. However, after entering a surname, the program stops immediately. From my understanding, Console.Read() should return an int value of the first character of the string I enter (ASCII code?).
Why does the program terminate right after Console.Read()? Shouldn't Console.ReadLine() ensure the program stays open? I am using Visual Studio 2012.
When you tell the console to enter your surname you are asking for a single character.
Console.Write("Enter your surname: ");
int r = Console.Read();
This surely should be a ReadLine followed by another ReadLine before exit. You are probably entering the first character (into Read), followed by subsequent characters, then hitting enter to accept the surname but you are actually on the ReadLine that will exit. So:
class Program
{
static void Main(string[] args)
{
Console.Write("Enter your name: ");
string s = Console.ReadLine();
Console.WriteLine("Your name: " + s);
Console.Write("Enter your surname: ");
// change here
string surname = Console.ReadLine();
Console.WriteLine("Your surname: " + surname);
Console.ReadLine();
}
}
The program does not terminate after int r = Console.Read() for me.
Based on how the console application was run it will execute all the lines of code and then 'return'. Once done this will close the program as for all intents and purposes it has done what it needs to. It isn't going to sit around and be open when it has finished.
If you want it to keep the window open write Console.Readline() at the end and it will stay open, until some input has been done. I remember having this issue when I started out, and it's not a matter of the program closing unexpectedly, but rather you wanting to see the results in the console before it closes.

Categories