Clear console buffer between Console.ReadLine and Console.Read [duplicate] - c#

This question already has an answer here:
Clear Console Buffer
(1 answer)
Closed 1 year ago.
I'm a beginner in C# so please be patient with me. :) I'm practicing to write a simple C# code to understand how this language works. I have tried to read characters, integers and strings from console but between different tries/methods the buffer never empties. I would like to clear the buffer of console between each methods, for example:
using System;
namespace ElsoKonzolAppom
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Write something!");
string text1 = Console.ReadLine();
Console.WriteLine("Your text:" + text1);
//here, I would like to clear the buffer
int number1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Your first number:" + number1);
//here, I would like to clear the buffer
int number2 = Console.Read();
Console.WriteLine("Your second number:" + number2);
}
}
}
Probably this is something very trivial that I haven’t mastered yet.

As far i understood you want to clear input buffer? There is no method in console class for it. Try this:
while(Console.KeyAvailable)
Console.ReadKey(false); // skips previous inputs
Console.ReadKey(); // reads a new char
Use Console.ReadKey(true) if you don't want to print skipped chars.
If you want to clear the screen use:
Console.Clear()
Regards

you can use Console.ReadKey(false); // true = hide input

Related

Why does my random number generated keep changing in .NET Fiddle / dotnetfiddle? [duplicate]

This question already has an answer here:
Problem with DotNetFiddle and Console.ReadLine that causes a Re-run when pressing ENTER key
(1 answer)
Closed 1 year ago.
Here's my code:
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
Random r = new Random();
int Winner = r.Next(1, 10);
bool win = false;
while (win == false)
{
Console.WriteLine("Welcome to the game!! Please guess a number between 0 and 10. It is " + Winner + " to win!");
int Guess = int.Parse(Console.ReadLine());
if (Guess == Winner)
{
Console.WriteLine("Well done! " + Guess + " is correct!!");
win = true;`enter code here`
}
else if (Guess > Winner)
{
Console.WriteLine("Guess lower!!");
}
else if (Guess < Winner)
{
Console.WriteLine("Guess higher!!");
}
}
}
}
The logic works, but the random integer changes each time it goes around the loop.
You can see this here: https://dotnetfiddle.net/vNrvho
Every time the loop goes around & Console.WriteLine("Welcome to the game!! Please guess a number between 0 and 10. It is " + Winner + " to win!") is ran again, the random number in the previous Console.WriteLine changes as well.
Why does the random number keep changing?
This is not an issue with your code, but an issue with .NET Fiddle.
You can also see the same issue replicated in another fiddle here, which does something similar: https://dotnetfiddle.net/Mn7mtT
The way that .NET Fiddle works is unknown to me but it's probably sending console output in a request on every input, changing the previous output somehow server-side and then giving you the illusion that the code is running input after input.
However, it's not & it's running the entire code again & again.
This will yield different random values of course and make you think that the value of Winner is changing every time while it isn't.
Verify this by noticing the changing Last Run: value every time you input a new number or by running the code locally outside of .NET Fiddle.
This happens regardless of project type or compiler settings in .NET Fiddle.
The lesson is don't always trust .NET Fiddle!

C# double value displaying incorrect value [duplicate]

This question already has answers here:
Difference between Console.Read() and Console.ReadLine()?
(12 answers)
Closed 1 year ago.
Hello I am practicing with C$ specifically with decimal numeric values. I have this simple program just to check if the inputted data is correct. I input 12.9 but get 49. Any help would be appreciated.
static void Main(string[] args)
{
Console.Write("Enter the first number 1: ");
double num1 = Console.Read();
Console.Write(num1);
//Console.WriteLine(num1+" + "+num2+" + "+num3 + " = "+total);
}
You need to use Console.ReadLine() and not Console.Read().
Read method - Reads the next character from the standard input stream.
ReadLine method - Reads the next line of characters from the standard input stream.
Try this:
static void Main(string[] args)
{
Console.Write("Enter the first number 1: ");
// It might cause an error if the user doesn't write a number
// which is parsable to double
double num1 = double.Parse(Console.ReadLine());
Console.Write(num1);
}
Or a safe way:
static void Main(string[] args)
{
Console.Write("Enter the first number 1: ");
// You may also ask the user to write again an input of number.
if (double.TryParse(Console.ReadLine(), out double num1))
{
Console.Write(num1);
}
}

Switch jumping to default case [duplicate]

This question already has answers here:
Difference between Console.Read() and Console.ReadLine()?
(12 answers)
Closed 1 year ago.
I don't get why my integer isn't coming out correctly, Console.Read() method says it's returning an integer, why isn't WriteLine displaying it correctly?
int dimension;
dimension = Console.Read();
Console.WriteLine(""+ dimension);
Console.Read() only returns the first character of what was typed. You should be using Console.ReadLine():
Example:
int suppliedInt;
Console.WriteLine("Please enter a number greater than zero");
Int32.TryParse(Console.ReadLine(), out suppliedInt);
if (suppliedInt > 0) {
Console.WriteLine("You entered: " + suppliedInt);
}
else {
Console.WriteLine("You entered an invalid number. Press any key to exit");
}
Console.ReadLine();
Additional Resources:
MSDN - Console.Read()
MSDN - Console.ReadLine()
From the MSDN:
Return Value
Type: System.Int32 The next character from the input stream, or
negative one (-1) if there are currently no more characters to be
read.
Your program is returning but you're not seeing, would you please see below code block:
You are not be able to see the output if the output window doesn't stay.
int dimension;
dimension = Console.Read();
Console.WriteLine("" + dimension);
Console.ReadLine();
Console.Read() returns ASCII code of first symbol in input. You can do
int dimension;
dimension = Console.Read();
Console.WriteLine(""+ (char)dimension);
and you'll see right first symbol in input, as
(char)dimension
will give you symbol by it's ASCII code.
int a = 0;
if(Int32.TryParse(Console.ReadLine(), out a))
{
// Do your calculations with 'a'
}
else
{
// Some warnings
}
The Console.Read method returns only a single character wrapped in an int, so that is only applicable if you are reading a number that is only one digit long, otherwise you'll always get only the first digit.
Since the return value of Read is actually a character, you cannot use it directly as an integer, you would need to parse it from character to integer.
But assuming that you want a number that is longer than one digit, then you really need to use Console.ReadLine instead and convert the input to an integer using int.TryParse. If int.TryParse returns false you can warn the user that he provided an invalid input and ask for the dimension again.
Sample code:
int dimension;
bool isValidDimension;
do
{
Console.Write("Dimension: ");
string input = Console.ReadLine();
isValidDimension = int.TryParse(input, out dimension);
if (!isValidDimension)
{
Console.WriteLine("Invalid dimension... please try again.");
Console.WriteLine();
}
} while (!isValidDimension);
you should it as follow
static void Main()
{
int Number;
string strNumber;
strNumber = Console.ReadLine();
Number = int.Parse(strNumber);
Console.WriteLine("" + dimension);
}

Could someone explain why Converting to int and using read line instead of Read fixed my issue?

So previous I was having a ton of trouble with finding the difference between a randomly generated number and user input. I did a little search and found that I couldn't use Console.Read(); and that I actually had to use this int guess = Convert.ToInt32(Console.ReadLine()); While playing around with it i accidentally made it Convert.ToInt32(Console.Read()); which was in turn making the math completely wrong. Apologies if I'm not explaining myself effectively I'm new to coding and this was meant to be something to learn from. Thanks!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Would you like to play the guessing game?");
string input = Console.ReadLine();
if (input.Equals("yes"))
{
Console.WriteLine("Alright! The rules are simple, i'll think of a number and you guess it!");
Console.WriteLine("Alright enter your guess: ");
int guess = Convert.ToInt32(Console.ReadLine());
Random rand = new Random();
int answer = rand.Next(1,11);
if (rand.Equals(guess))
{
Console.WriteLine("Congratulations you guessed correctly!");
}
else
{
Console.WriteLine("Aww you were so close! I guessed " + answer);
int difference = guess - answer;
Console.WriteLine("you were only " + Math.Abs(difference) + " away");
}
} else
{
Console.WriteLine("Closing application...");
Thread.Sleep(1000);
Environment.Exit(0);
}
}
}
}
Console.Read()
Returns you the ascii value of a single character being input.
For example, entering 'A' would return 65. See here for a list of ascii codes. Note that the ascii value for 1 is actually 49.
Convert.ToInt32(Console.ReadLine());
Reads the entire line and tries to convert it to an integer.
Console.Read() will grab just one character and Console.ReadLine() takes the whole line or everything the user types until it found the "Enter" key pressed.
Becuase Console.Read reads in characters from the console. It returns, as an integer. So when you enter "yes" the output will be
121 = y
101 = e
115 = s
13 =
10 =
The final two characters (13 and 10) are equal to the Windows newline.

Console.Read not returning my int32 [duplicate]

This question already has answers here:
Difference between Console.Read() and Console.ReadLine()?
(12 answers)
Closed 1 year ago.
I don't get why my integer isn't coming out correctly, Console.Read() method says it's returning an integer, why isn't WriteLine displaying it correctly?
int dimension;
dimension = Console.Read();
Console.WriteLine(""+ dimension);
Console.Read() only returns the first character of what was typed. You should be using Console.ReadLine():
Example:
int suppliedInt;
Console.WriteLine("Please enter a number greater than zero");
Int32.TryParse(Console.ReadLine(), out suppliedInt);
if (suppliedInt > 0) {
Console.WriteLine("You entered: " + suppliedInt);
}
else {
Console.WriteLine("You entered an invalid number. Press any key to exit");
}
Console.ReadLine();
Additional Resources:
MSDN - Console.Read()
MSDN - Console.ReadLine()
From the MSDN:
Return Value
Type: System.Int32 The next character from the input stream, or
negative one (-1) if there are currently no more characters to be
read.
Your program is returning but you're not seeing, would you please see below code block:
You are not be able to see the output if the output window doesn't stay.
int dimension;
dimension = Console.Read();
Console.WriteLine("" + dimension);
Console.ReadLine();
Console.Read() returns ASCII code of first symbol in input. You can do
int dimension;
dimension = Console.Read();
Console.WriteLine(""+ (char)dimension);
and you'll see right first symbol in input, as
(char)dimension
will give you symbol by it's ASCII code.
int a = 0;
if(Int32.TryParse(Console.ReadLine(), out a))
{
// Do your calculations with 'a'
}
else
{
// Some warnings
}
The Console.Read method returns only a single character wrapped in an int, so that is only applicable if you are reading a number that is only one digit long, otherwise you'll always get only the first digit.
Since the return value of Read is actually a character, you cannot use it directly as an integer, you would need to parse it from character to integer.
But assuming that you want a number that is longer than one digit, then you really need to use Console.ReadLine instead and convert the input to an integer using int.TryParse. If int.TryParse returns false you can warn the user that he provided an invalid input and ask for the dimension again.
Sample code:
int dimension;
bool isValidDimension;
do
{
Console.Write("Dimension: ");
string input = Console.ReadLine();
isValidDimension = int.TryParse(input, out dimension);
if (!isValidDimension)
{
Console.WriteLine("Invalid dimension... please try again.");
Console.WriteLine();
}
} while (!isValidDimension);
you should it as follow
static void Main()
{
int Number;
string strNumber;
strNumber = Console.ReadLine();
Number = int.Parse(strNumber);
Console.WriteLine("" + dimension);
}

Categories