Sign in to follow this  
goolulusaurs

new to c#

Recommended Posts

goolulusaurs    122
I wrote this program a few minutes ago and for some reason it allways adds 48 to what ever I input i dont know if i should be useing another function or somthing i havent seen in any tutrials or books how to input ints heres the code: class Helloworld { static void Main() { int num=0; System.Console.Write("enter a number:"); num = System.Console.Read(); System.Console.WriteLine("you entered " + num); System.Console.ReadKey(); } }

Share this post


Link to post
Share on other sites
Scet    960
Console.Read returns the ASCII value of the next character in the stream, and the zero character is 48, one is 49 and so on. I'm pretty sure the method to read integers is to read a string and then convert it. Considering the size of the .NET API, you'd think they'd put a ReadInt32() function in there.

Share this post


Link to post
Share on other sites
Nypyren    12074
There is a function called Int32.Parse(string), and probably one called TryParse.

If you use TryParse it won't throw an exception if it fails. I can't remember if all of the types have that function though.

(edit) OK, it has TryParse.

So what you do is this:


int value1;

string text = Console.ReadLine();

bool success = Int32.TryParse(text, out value1);

if (success)
{
Console.WriteLine("you entered "+value1);
}
else
{
Console.WriteLine("That is not a number!");
}



(edit2)

You can write "int" instead of "Int32" and it will work the same. Creepy!

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this