Console.Read() Problem

  • Thread starter Thread starter Jerry
  • Start date Start date
J

Jerry

I am having problem with Console.Read(), the Value I
entered is not the value that store in my variable.

public class Num
{
int num;
Console.Write("Enter a number: ");
num=Console.Read();
Console.WriteLine("{0}",num)

}

every time i test this code, I enter 1, but the value
store in num is 49, which mean i got 49 as output, i
enter 2, I got 50. does anyone know, why this happen and
any solutions for it. it sounds like the program take 1
and converted to ascII code, and stored at num. Help
please, thank you.
 
Hi Jerry,

Console.Read() usually returns the input character, which in your
case is the ASCII value of the interger that you entered.
Please try reading the input as a string and then use one of the
Convert.XXX functions to convert to your required type.

Console.Write("Enter a number: ");
String numAsString = Console.ReadLine();
Console.WriteLine("Number is {0}", Convert.ToInt32(numAsString));

Hope this helps.

Regards,
Aravind C
 
Hi,

That is the correct behaviour, Console.Read() returns the character entered,
in your case the character code for 1 is correctly returned as 49. If you
want the number you can either subtract 48 (I am not really recommending
this!). You could use ReadLine and use Int32.Parse() or Convert functions to
convert from the input string to an integer.. If you can be more specific as
to your requirements myself or someone else might be able to give a more
specific solution.

Hope this helps

Chris Taylor
 
Well, Console.Read returns an int representing the character entered.
A couple of possibilities are

public class Num
{
int num;
Console.Write( "Enter a number: " );
num = Console.Read();
if(num < 58 & num > 47)
{
num -= 48;
Console.WriteLine( "{0}", num )
// I prefer WriteLine( num );
}
}

public class Num
{
int num;
Console.Write( "Enter a number: " );
num = Console.Read();
if(num < 58 & num > 47)
{
Console.WriteLine( "{0}", (char)num )
}
}
 
Back
Top