I copied you code and tested it.
even though i input the
integer
values it was giving the same
format exception
..
Consider
Solution 1,2,3 for information regarding
Parsing Integer values
the problem is that, you are using
Console.Read()
method
Quote:
The Read method blocks its return while you type input characters; it terminates when you press the Enter key. Pressing Enter appends a platform-dependent line termination sequence to your input (for example, Windows appends a carriage return-linefeed sequence). Subsequent calls to the Read method retrieve your input one character at a time. After the final character is retrieved, Read blocks its return again and the cycle repeats.
Refer
Console.Read Method (System)[
^]
try debugging this below code
class Program
{
static void Main(string[] args)
{
Console.WriteLine("hello");
Console.WriteLine("enter the character");
int c = Console.Read();
Console.WriteLine(c);
Console.WriteLine("please enter first integer");
string p1str = Console.ReadLine();
int p1 = Convert.ToInt32(p1str);
Console.WriteLine("second");
string p2str = Console.ReadLine();
int p2 = Convert.ToInt32(p2str);
Console.WriteLine(p1 + p2);
}
}
The
Console.Read()
will be assigning the last char value in that line.
and the immediate
Console.ReadLine()
will be ignored from the User Input and it assigns the value which is already typed on the screen.
for example:
if you type "
a1
" then the
p1str
will be holding the value "
1
" by ignoring the first char
if you type "
123
" then the
p1str
will be holding the value "
23
" which can be parsed to integer without exception.
if you type "
1[pressed enter key]
" then
p1str
will be holding the value "" (empty or return key ) which will result in
format exception
..
I hope you understood, apply breakpoint and debugger, witness it how it works..