Reputation: 45
I'm running a very simple program that just prompts the user for a number, and for now, just prints it on the screen. But for some reason that I do not know of, the number i enter seems to add to the number 48.
for example: I enter 2 and it puts out 50
Is there some sort of fundamental law that I'am overseeing, or some sort of mistake I've made in my code
I'm a beginner, if you hadn't noticed
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
int Num;
Console.WriteLine("Please Input Number of Rows you want to make in your pyrimid: ");
Num = Console.Read();
Console.WriteLine(Num);// Just to check if it is getting the right number
Console.Read();//This is Here just so the console window doesn't close when the program runs
}
}
}
edit: Hate to be a bother but now getting this error for num = int.Parse(Console.Read());
as The best overloaded method match for 'int.Parse(string)' has some invalid arguments. Does this mean that i need an overload method?
Upvotes: 0
Views: 135
Reputation: 150313
Console.Read
returns char
so when you cast it to int
yo get the ASCII code of 2
which is 50! You should parse to int instead of (implicitly) casting it:
Num = int.Parse(Console.Read());
Notes:
int.TryParse
Num
to num
.Upvotes: 5
Reputation: 20595
Console.Read
reads reads byte from Standard Input.
2
has a ASCII value of 50
You need to parse the value read from the console
Num = Int32.Parse(Console.Read()); // or Num = int.Parse(Console.Read());
Upvotes: 0
Reputation: 21495
Console.Read
returns the character code and not the character itself.
char num = (char)Console.Read();
Console.WriteLine(int.Parse(num.ToString()));
This code is not ideal but it shows what is happening. Since you are expecting a digit to be entered you can also use
int num = Console.Read() - 48;
Upvotes: 1