I am switching from Python to C# and I am having trouble with the ReadLine()
function. If I want to ask a user for input Python I did it like this:
x = int(input("Type any number: "))
In C# this becomes:
int x = Int32.Parse (Console.ReadLine());
But if I type this I get an error:
int x = Int32.Parse (Console.ReadLine("Type any number: "));
How do I ask the user to type something in C#?
You should change this:
int x = Int32.Parse (Console.ReadLine("Type any number: "));
to this:
Console.WriteLine("Type any number: "); // or Console.Write("Type any number: "); to enter number in the same line
int x = Int32.Parse(Console.ReadLine());
But if you enter some letter(or another symbol that cannot be parsed to int
) you will get an Exception
. To check if entered value is correct:
(Better option):
Console.WriteLine("Type any number: ");
int x;
if (int.TryParse(Console.ReadLine(), out x))
{
//correct input
}
else
{
//wrong input
}