Skip to main content
gamedev.net
🔒 Locked

[.net] Console.Read

Started by sevak Dec 21, 2004 at 5:26 PM 0 replies 800+ views
Original Post
sevak
sevak
I have this problem with this peice of code. If I type 5 shouldn't 5 be displayed on the console window? When I type 5 I get back 53.

using System;

class ReadNumberFromConsole
{
  static void Main()
  {
    
    Int32 I;
    Console.Write("Enter a number: ");
    I = Console.Read();
    Console.WriteLine(I);
  }
}


www.computertutorials.org
computertutorials.org-all your computer needs...
kSquared
kSquared
Quote:
Original post by sevak
I have this problem with this peice of code. If I type 5 shouldn't 5 be displayed on the console window? When I type 5 I get back 53.

*** Source Snippet Removed ***

You're storing the integer value of the character '5' (which is 53), not the integer value 5. To do that, try this:

    public static void Main(string[] args)    {      Int32 i;      Console.WriteLine("Enter a number:");      try      {        i = Int32.Parse(Console.ReadLine());      }      catch (OverflowException e)      {        Console.WriteLine("The value read was unable to fit in an Int32.");      }      catch (FormatException e)      {        Console.WriteLine("The value read was not an integer.");      }      Console.WriteLine("The value retrieved was {0}.", i);    }


HTH,
- k2 "Choose a job you love, and you'll never have to work a day in your life." — Confucius"Logic will get you from A to B. Imagination will get you everywhere." — Albert Einstein"Money is the most egalitarian force in society. It confers power on whoever holds it." — Roger Starr{General Programming Forum FAQ<

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.