Reputation: 393
I've recently started to code in C#, so I'm just learning the basics right now. I've tried to search for this through Google and on this site, however, I couldn't find any solutions, but basically when I do Console.Read(), and take in an input and store it into an integer variable, the value I input is strangely different when it is outputted.
Here is the block of code I am trying to run:
Console.WriteLine("Welcome To The Program!");
Console.Write("Enter the radius of the sun: ");
input = Console.Read();
Console.WriteLine(input);
Console.ReadKey();
Input is a type of int and when I type in say 5, it will output 53. If I input 0, it will output 48.
Can anyone please explain why this may be happening? I know there is a way to parse input by first taking it as a string input and then parsing it as an integer, but that would take too long for larger pieces of code.
Upvotes: 1
Views: 6682
Reputation: 2458
If you only want to read one character at a time, then you can use the following:
int input = int.Parse(((char)Console.Read()).ToString());
This gets the character of the code point and then turns it into a string before it is parsed. However, if you are going to have more than one character or there is any chance that the input won't be a number, then you should look at HeshamERAQI's response.
Upvotes: -1
Reputation: 2542
For the record, the reason this didn't work is because Console.Read returns the ASCII integer representation of the first character entered in the console. The reason that "5" echoed 53 to the screen is this:
Console.Read begins reading from the console's In stream. The first character in the stream is '5'. The ASCII value of '5' is 53. "input" is assigned the value of 53.
This should solve your problem:
input = int.Parse(Console.ReadLine());
You can also better use this:
int number;
if(!int.TryParse(Console.ReadLine(), out number)){
Console.WriteLine("Input was not an integer.");
return;
}
Console.WriteLine(number);
Upvotes: 2
Reputation: 688
You are receiving the ASCII value of the character in question. In order to get what you want, you have to accept a string and then parse it. It will take less time than you think.
Upvotes: 1
Reputation: 8431
Put it inside Convert.ToInt32
since you are reading the line as string value like this:
input = Convert.ToInt32(Console.Read());
Upvotes: 4