new to c#

Started by
2 comments, last by Nypyren 16 years, 1 month ago
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(); } }
Advertisement
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.
thanks
I try
num = (int) System.Console.ReadLine();
but it said cannot convert string to int
how would I do the conversion?
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!

This topic is closed to new replies.

Advertisement