Strange behaviour from Console.ReadKey() - c#

The output looks something like:
] [ Your input is: ffffffwwqqqwffasfffffffw
>
when you use BACKSPACE which shouldn't be possible to begin with,
why is this happening
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ConsoleApp7
{
class Program
{
public static string input;
static Program()
{
input = string.Empty;
}
static void Main(string[] args)
{
while (true)
{
ConsoleKeyInfo consoleKeyInfo;
Console.Clear();
Console.Out.Write($"\r\n\t[ Your input is: {input} ]\r\n\r\n\t>");
consoleKeyInfo = Console.ReadKey();
if (consoleKeyInfo.Modifiers == default(ConsoleModifiers))
input += consoleKeyInfo.KeyChar;
Thread.Sleep(250);
}
}
}
}

Backspace is a valid char for ReadKey to process, and when you concatenate a backspace char to the string, it will remove the last character from the string in the output. You can check whether the key that was pressed was a backspace and ignore it.
if (consoleKeyInfo.Modifiers == default(ConsoleModifiers) && consoleKeyInfo.Key != ConsoleKey.Backspace)
input += consoleKeyInfo.KeyChar;

Related

Program that writes numbers until I write a string to stop it

I am required to write a program that prints out numbers until I write in the console window a simple string "stop". The numbers are supposed to go on infinitely until the condition is met.
I tried:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp3
{
internal class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 1000000000;)
{
Console.WriteLine(i);
string a = Console.ReadLine();
if (a == "stop")
{
break;
}
i++;
}
}
}
}
But, there is a delay waiting for my input every time, it's not constant.
You are asking for a non blocking console read. THats not simple.
One way is to peek to see if a key is available to read
int number = 0;
while (true)
{
Console.WriteLine(number);
number++;
if (Console.KeyAvailable)
{
var s = Console.ReadLine();
if (s == "stop")
break;
}
}

How could i replace a number with it's matching month name in c#? [duplicate]

This question already has answers here:
Get Month name from month number
(9 answers)
Closed 5 years ago.
So i have a program that asks for your birth data and i want to replace the number of the month to its matching name. For ex. if someone writes 1989.11.10 then the result would be 1989. november 10.
My code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
namespace hf
{
class Program
{
static void Main(string[] args)
{
Console.Write("Bith data: ");
string adat = Console.ReadLine();
string szido = Regex.Replace(adat, "[^0-9.]", "");
Console.WriteLine("Birthday: {0}", szido);
string[] szidotomb = new string[3];
szidotomb = szido.Split('.');
for (int i = 0; i < 3; i++)
Console.WriteLine(szidotomb[i]);
Console.ReadKey();
}
}
}
No need to, you can use DateTime.ToLongDateString or .ToString
Read your user's input from the console, then use DateTime.tryParse the string, and then print it with the aforementioned method of the class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using System.Globalization;
public class Program
{
public static void Main()
{
DateTime dt = new DateTime();
string userInput;
do
{
Console.Write("Please enter your birth date in YYYY.MM.DD format: ");
userInput = Console.ReadLine();
}
while (!DateTime.TryParseExact(userInput, "yyyy.MM.dd",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt));
Console.WriteLine("You were born on: \"{0}\"\n", dt.ToString("yyyy.MMMM.dd"));
Console.ReadLine();
}
}
You can run an example here

Avoid writing of equal existing line to text document

I’m new with C# need your help
In this code, I write a some word or phrase to text document with cycle loop. My question is how to avoid writing of equal line, which is already exist in text document and find it in text document, show on output?
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace program_1
{
class Program
{
static void Main(string[] args)
{
int i = 0;
for (;;)
{
Console.Write("Write phrase: ");
var row = Console.ReadLine();
Console.WriteLine(i++ + ". " + (row));
TextWriter tsw = new StreamWriter("lines.txt", true);
tsw.WriteLine(row);
tsw.Close();
}
Console.Read();
}
}
}
If you want to avoid writing duplicate lines in your file, you need a different approach. First, you need to have all of your lines in memory, then check if the user inputs a line already in memory, then write everything at the end of the program
class Program
{
static void Main(string[] args)
{
int i = 0;
List<string> wordsTyped = new List<string>();
// If the file already exists then you can load its content
// in memory to start your checks against the current content
// of the file....
if(File.Exists("lines.txt"))
wordsTyped.AddRange(File.ReadAllLines("lines.txt"));
for (;;)
{
Console.Write("Write phrase: (type 'exit' to end)");
string row = Console.ReadLine();
// Provide a way to exit from this infinite loop
if(row == "exit")
break;
Console.WriteLine(i++ + ". " + (row));
// Use IndexOf to find if there is a match for your row
// and in which position in the List<string>
int position = wordsTyped.IndexOf(row);
if (position != -1)
Console.WriteLine($"Already inserted. Found match at line {position+1} , type again");
else
{
wordsTyped.Add(row);
// It of uttermost importance to enclose the StreamWriter
// in a using statement to be sure to close and dispose it
// after the write, otherwise you could lock yourself out
using(StreamWriter sw = File.AppendText("lines.txt"))
sw.WriteLine(row);
}
}
// File.WriteAllLines("lines.txt", wordsTyped.ToArray());
Console.Read();
}
}

C# repeat or close program based on input - Temperature Conversion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("What is the Temperature in Fahrenheit?")
string input = Console.ReadLine ();
double tt = double.Parse (input);
double cc = (tt-32)*5/9;
Console.WriteLine(cc + " is the temperature in Celsius");
}
}
}
My problem is, I need to receive input and close out if I don't. If their input is (""), the program needs to close, but if they input a number - e.g. 13, I need to have the program loop back to the beginning until I get an input of (""), at which point the program closes. I'm fairly new to programming, but I've tried everything I can think of to try/figure out, so any help you can give would be greatly appreciated.
Try:
Console.WriteLine("What is the Temperature in Fahrenheit?")
string input = Console.ReadLine ();
while (input != "")
{
double tt = double.Parse (input);
double cc = (tt-32)*5/9;
Console.WriteLine(cc + " is the temperature in Celsius");
Console.WriteLine("What is the Temperature in Fahrenheit?")
input = Console.ReadLine ();
}
if instead you use a specific character to specify ending the program instead of an empty line, it is relatively easy:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string exit = "";
while(exit.ToLower != "no")
{
Console.WriteLine("What is the Temperature in Fahrenheit?");
string input = Console.ReadLine();
double tt = double.Parse (input);
double cc = (tt-32)*5/9;
Console.WriteLine(cc + " is the temperature in Celsius");
Console.WriteLine("if you want to do another conversion, enter \"yes\" otherwise, enter \"no\"");
exit = Console.ReadLine();
}
}
}
}

C# Console.ReadKey 1 character lag?

I'm attempting to work with the Console.ReadKey() function in order to intercept the user's keystrokes and rebuild what they are typing on the screen (as I'll need to clear the screen often, move the cursor often, and this seemed like the most full-proof method of making sure what they typed didn't vanish or appear at random points all over the screen.
My question is: Has anyone else ever experienced a 1 character "lag", for lack of a better term, when doing something similar? Say I want to type the word "This". When I press "T", nothing shows up, no matter how long I wait. When I press "h", the "T" appears. "i", the "h" appears. The letter I type will not appear until I hit another key, even if that key is the space bar. Does anyone have any suggestions for what I am doing wrong? I'm sure it has to do with how I am using Console.Readkey, I just don't see what alternative would work. I have attached a small and simple example of this below.
Thank you!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleApplication2
{
class Program
{
private static string userInput = "";
static ConsoleKeyInfo inf;
static StringBuilder input = new StringBuilder();
static void Main(string[] args)
{
Thread tickThread = new Thread(new ThreadStart(DrawScreen));
Thread userThread = new Thread(new ThreadStart(UserEventHandler));
tickThread.Start();
Thread.Sleep(1);
userThread.Start();
Thread.Sleep(20000);
tickThread.Abort();
userThread.Abort();
}
private static void DrawScreen()
{
while (true)
{
Console.Clear();
Console.SetCursorPosition(0, 0);
Console.Write("> " + userInput);
Thread.Sleep(300);
}
}
private static void UserEventHandler()
{
inf = Console.ReadKey(true);
while (true)
{
if (inf.Key != ConsoleKey.Enter)
input.Append(inf.KeyChar);
else
{
input = new StringBuilder();
userInput = "";
}
inf = Console.ReadKey(true);
userInput = input.ToString();
}
}
}
}
It is because you have 2 times Console.ReadKey()
If you change your code into this
private static void UserEventHandler()
{
while (true)
{
inf = Console.ReadKey(true);
if (inf.Key != ConsoleKey.Enter)
input.Append(inf.KeyChar);
else
{
input = new StringBuilder();
userInput = "";
}
userInput = input.ToString();
}
}
It does not lag. the second Console.ReadKey() is blocking in your code. I did not check if you need the parameter true to the readkey, that's for you to find out

Categories