Console.Read() and Console.ReadLine() problems [duplicate] - c#

This question already has answers here:
Console.Read not returning my int32 [duplicate]
(7 answers)
Closed 1 year ago.
I have been trying to use Console.Read() and Console.ReadLine() in C# but have been getting weird results. for example this code
Console.WriteLine("How many students would you like to enter?");
int amount = Console.Read();
Console.WriteLine("{0} {1}", "amount equals", amount);
for (int i=0; i < amount; i++)
{
Console.WriteLine("Input the name of a student");
String StudentName = Console.ReadLine();
Console.WriteLine("the Students name is " + StudentName);
}
has been giving me that amount = 49 when I input 1 for the number of students, and Im not even getting a chance to input a student name.

This because you read a char.
Use appropriate methods like ReadInt32() that takes care of a correct conversion from the read symbol to the type you wish.
The reason why you get 49 is because it's a char code of the '1' symbol, and not it's integer representation.
char code
0 : 48
1 : 49
2: 50
...
9: 57
for example: ReadInt32() can look like this:
public static int ReadInt32(string value){
int val = -1;
if(!int.TryParse(value, out val))
return -1;
return val;
}
and use this like:
int val = ReadInt32(Console.ReadLine());
It Would be really nice to have a possibility to create an extension method, but unfortunately it's not possible to create extension method on static type and Console is a static type.

Try to change your code in this way
int amount;
while(true)
{
Console.WriteLine("How many students would you like to enter?");
string number = Console.ReadLine();
if(Int32.TryParse(number, out amount))
break;
}
Console.WriteLine("{0} {1}", "amount equals", amount);
for (int i=0; i < amount; i++)
{
Console.WriteLine("Input the name of a student");
String StudentName = Console.ReadLine();
Console.WriteLine("the Students name is " + StudentName);
}
Instead to use Read use ReadLine and then check if the user input is really an integer number using Int32.TryParse. If the user doesn't input a valid number repeat the question.
Using Console.Read will limit your input to a single char that need to be converted and checked to be a valid number.
Of course this is a brutal example without any error checking or any kind of safe abort from the loops.

For someone who might still need this:
static void Main(string[] args)
{
Console.WriteLine("How many students would you like to enter?");
var amount = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("{0} {1}", "amount equals", amount);
for (int i = 0; i < amt; i++)
{
Console.WriteLine("Input the name of a student");
String StudentName = Console.ReadLine();
Console.WriteLine("the Students name is " + StudentName);
}
}

you get a character char from read not an int. you will need to make it a string first and parse that as a string. THe implementation could look like the below
Console.WriteLine("How many students would you like to enter?");
var read = Console.ReadLine();
int amount;
if(int.TryParse(read,out amount)) {
Console.WriteLine("{0} {1}", "amount equals", amount);
for (int i=0; i < amount; i++)
{
Console.WriteLine("Input the name of a student");
String StudentName = Console.ReadLine();
Console.WriteLine("the Students name is " + StudentName);
}
}
I've changed it to use readline because readline returns a string an doesn't arbitrarily limits the number of students to 9 (the max number with one digit)

Console.Read() is returning the char code of the character that you enter. You need to use Convert.ToChar(amount); to get the character as a string, and then you will need to do int.Parse() to get the value you're looking for.

Console.Read returns the asci value of the key character that was pressed.
If you use Console.ReadKey().KeyChar you'll get a char that represents the actual character that was pressed.
You can then turn that character to a one character string by using .ToString().
Now that you have a string you can use int.Parse or int.TryParse to turn a string containing entirely numeric characters into an integer.
So putting it all together:
int value;
if (int.TryParse(Console.ReadKey().KeyChar.ToString(), out value))
{
//use `value` here
}
else
{
//they entered a non-numeric key
}

Instead of:
int amount = Console.Read();
try:
int amount = 0;
int.TryParse(Console.ReadLine(), out amount);
Its because You read just character code, so for example typing 11 You will still get 49. You need to read string value and the parse it to int value. With code above in case of bad input You will get 0.

Try this:
int amount = ReadInt32();
or if it doesn't work try this:
int amount = Console.ReadInt32();
or this:
int amount = Convert.ToInt32(Console.Readline());
In this, it will read string then it will convert it into Int32 value.
You can also go here: http://www.java2s.com/Tutorials/CSharp/System.IO/BinaryReader/C_BinaryReader_ReadInt32.htm
If nothing works, please let me know.

Console.WriteLine("How many students would you like to enter?");
string amount = Console.ReadLine();
int amt = Convert.ToInt32(amount);
Console.WriteLine("{0} {1}", "amount equals", amount);
for (int i = 0; i < amt; i++)
{
Console.WriteLine("Input the name of a student");
String StudentName = Console.ReadLine();
Console.WriteLine("the Students name is " + StudentName);
}
//thats it

TL;DR; Enter key in Windows isn't a single character. This fact is at the root of many issues related to Console.Read() method.
Complete Details:
If you run below piece of code on your computer then you can solve lot of mysteries behind Console.Read():
static void Main(string[] args)
{
var c = Console.Read();
Console.WriteLine(c);
c = Console.Read();
Console.WriteLine(c);
}
While running the program, hit the Enter key just once on your keyboard and check the output on console. Below is how it looks:
Interestingly you pressed Enter key just once but it was able to cater to two Read() calls in my code snippet. Enter key in windows emits two characters for a new line character namely carriage return (\r - ASCII code 13) and line feed (\n - ASCII code 10). You can read about it more here in this post - Does Windows carriage return \r\n consist of two characters or one character?

Related

How to multiply correctly two numbers in a method?

{
Console.ForegroundColor= ConsoleColor.Yellow;
Console.BackgroundColor = ConsoleColor.DarkRed;
Console.Clear();
Console.WriteLine("Please enter your name and I will tell you how many letters your name has!");
string name = Console.ReadLine();
Count(name);
Console.WriteLine("Now tell me two numbers and I will multiply them!");
Console.Read();
try
{
Multiply();
}
catch (FormatException)
{
Console.WriteLine("You must enter a number!");
}
}
public static void Count(string name)
{
Console.WriteLine("Your name has {0} letters!", name.Length);
}
public static void Multiply()
{
string firstNum = Console.ReadLine();
string secondNum = Console.ReadLine();
int num = Int32.Parse(firstNum);
int num1 = Int32.Parse(secondNum);
int result = num * num1;
Console.WriteLine("The result is {0}", result);
}
Im a beginner and Im learning about methods so I made this simple code where the user should enter two numbers and I should multiply them, the problem is, whenever I enter two random numbers, I am getting some completely different numbers back no matter if i want to add them, multiply them or something third.
I cannot figure out why the "num1 * num2;" is not giving me a correct number. E.G. 54*19 should give me 1026, but instead its giving me -15.
you need to comment on the Console.Read(); line. this is the main cause.
I have run your code by commenting on the above line and it works as expected for me
Also, you need to handle the scenarios when the user can enter a non-integer input, so you could use int.TryParse for the same.
Also, try to handle the scenario where the integer value is very large and the multiplication of two numbers exceeds the integer max value.

How to use same variable for string input in one case, and int input in another case? (C#)

Quick question how do I use same variable for string input in case and int input in another case. Here is what I mean by that, I have a problem where I need to constantly insert number and then put the addition of those numbers inside another variable. This inserting is inside do while loop, for me to exit the loop and to show the sum of those numbers, I need to type "OK" or "ok". I have a problem where I do not know how to use string variable for int inputs.
Here is my code:
string input= "";
int sum = 0;
do
{
Console.WriteLine("Insert the number or OK (ok) for exit: ");
input = Console.ReadLine();
sum += Convert.ToInt32(input);
// this is where I get the error Input string was not in the correct fromat
} while (input != "OK" && input != "ok");
Console.WriteLine(sum)
If anyone knows how to help me with this, I would gladly appreciate it.
First identify that the user entered integer or not using int.TryParse(), if user entered integer then add it to the sum variable otherwise check the string
do
{
Console.WriteLine("Insert the number or OK (ok) for exit: ");
input = Console.ReadLine();
//This will add number only if user enters integer.
if(int.TryParse(input, out int number)
sum += number
} while (input != "OK" && input != "ok");
You have to test for OK before you try to convert to a number, because OK won't convert to a number
string input= "";
int sum = 0;
while(true)
{
Console.WriteLine("Insert the number or OK (ok) for exit: ");
input = Console.ReadLine();
if("OK".Equals(input, StringComparison.OrdinalIgnoreCase)) //do a case insensitive check. Note that it's acceptable to call methods on constants, and doing a string check this way round cannot throw a NullReferenceException
break;//exit the loop
sum += Convert.ToInt32(input);
}
Console.WriteLine(sum);
You'll still get the error if the user enters input other than OK, that is not convertible to a number, but this is the crux of your current problem. I'll leave dealing with other garbages as an exercise for you...

Relational Operator Statement And Output Don't Seem To Match

Good day all, I'm new to C# and currently at the stage of experimenting with if-else statements. Upon declaring variables ageUser, permittedAge, input and running the program, I noticed that the if statement and the resulting output don't seem to match.
int ageUser;
int permittedAge = 18;
int input;
Console.Write("Put in your age: ");
input = Convert.ToInt32(Console.Read());
ageUser = input;
if (ageUser < permittedAge)
{
Console.WriteLine("Sorry you are not permitted to enter this site!");
}
else
{
Console.WriteLine("Welcome");
}
Link To Console Output
You will need to change how you read in the input. Read() reads in a character and does not convert that to int like you think it does. (5 becomes 53 due to its ASCII representation). Use ReadLine instead.
Use the folowing instead.
Console.Write("Put in your age: ");
input = Convert.ToInt32(Console.ReadLine());
ageUser = input;

Code won't give desired output or read second input

Sorry if this isn't the right. This is my first time posting here. I'm a first year Software student and for the life of me i cannot seem to get this to work. I know its something simple I'm missing but oh well. I tried doing this using methods but again no help. Maybe you guys could help me?
The problem is the code wont let me input after the "Are you a member (Y/N)" writline statement and just keeps giving me an output of 50.
static void Main(string[] args)
{
//Local Variable Declaration//
double rate1 = 10;
double rate2 = 3;
double maxCharge = 50;
double charge;
Console.WriteLine("Enter number of hours (-999 to quit) : ");
int hoursRented = Console.Read();
if (hoursRented >= 3)
{
charge = hoursRented * rate1;
}
else
{
charge = (3 * rate1) + (hoursRented * rate2);
}
if (charge > maxCharge)
{
charge = maxCharge;
}
Console.WriteLine("Are you a member? (Y/N) : ");
int memberStatus = Console.Read();
if (memberStatus.Equals("Y"))
{
charge = (charge * 1 / 10) - charge;
}
Console.WriteLine("Customer Charge : {0} Total Charge To Date : ", charge);
}
The problematic lines are below
Console.WriteLine("Enter number of hours (-999 to quit) : ");
int hoursRented = Console.Read();
if (hoursRented >= 3) {
and
Console.WriteLine("Are you a member? (Y/N) : ");
int memberStatus = Console.Read();
if (memberStatus.Equals("Y")) {
When you call Console.Read(), it reads only characters and returns it as an int. You seem to mistakenly think it will parse the character to an int.
Secondly, think what happens when you provide multiple characters as input to a single Console.Read() call. Interestingly, the remaining characters are read in the subsequent calls. So when you type any number followed by Enter in the first Console.Read it only, reads the first character, the subsequent characters, including the EOLN char are returned in the subsequent calls, instead of prompting you to enter information for the next call.
The fix is easy. Use Console.Readline() and int.parse (or its int.TryParse() variant
Then the corresponding code will look like below
Console.Write("Enter number of hours (-999 to quit) : ");
string hoursRentedStr = Console.ReadLine();
int hoursRented = int.Parse(hoursRentedStr);
if (hoursRented >= 3) {
and
Console.Write("Are you a member? (Y/N) : ");
string memberStatus = Console.ReadLine();
if (memberStatus.Equals("Y")) {
This is because you are just writing:
Console.WriteLine("Are you a member? (Y/N) : ");
and continuing through.
you must do it like this:
Console.WriteLine("Are you a member? (Y/N) : ");
Console.ReadLine();
and then:
int memberStatus = Int.Parse(Console.ReadKey());
your problem is that your are using Console.Read wich returns the ascii code of the next charachter as said by #juharr in the comments. so the solution is too simply replace Read By ReadLine and change your code like this, so that ReadLine wich is a string will be converted to the int value that you want
int hoursRented = int.Parse(Console.ReadLine());
And change your member status to a string to compare it with "Y" easily
string memberStatus = Console.ReadLine();
Note: if you want to validate the input you should use a int.TryParse instead of just a normal parse like I used as it returns a bool so you knows when it fails

double is an integer, difficulty parsing

This works perfectly, except that when the user enters an number with a decimal (e.g. 2.3), it returns the same statement ("Number must be an integer").
I am trying to say if it is not an int OR a double.
Code:
while (true)
{
Console.Write("Enter First Integer:");
string line = Console.ReadLine();
if (!int.TryParse(line, out firstNo)) //INT OR A DOUBLE
Console.WriteLine("Number must be an integer. {0} is not an integer.", line);
break;
}
Parse it as double, it would work both with integers and decimals:
double doubleVar;
while (true)
{
Console.Write("Enter First number:");
string line = Console.ReadLine();
if (!double.TryParse(line, out doubleVar)) //PARSE INT OR DOUBLE
Console.WriteLine("you must enter a number. {0} is not a number.", line);
else
break;
}
Remember that . or , separator may differ depending on your current culture.
So, if you need to separate int ans doubles, do smth like this:
if (int.TryParse(line, out intVar)) //PARSE INT
{
//it's int
}
else if (double.TryParse(line, out doubleVar)) //PARSE DOUBLE
{
//it's double
}
else
{
//it's not
}
Since all integers are doubles, you could just parse it as a double only.
try this simply trick,
bool result = line.Constains(".");
Whole numbers and Fractional numbers are two different entities.You should not mix up.
If you are looking for a way to support fractional and whole number inputs then try below
if (!double.TryParse(line, out firstNo))

Categories

Resources