Zech Zech - 1 day ago 3
C# Question

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);
}
}
}
}

Rob Rob
Answer
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.

Comments