Hi. I am trying to convert a user input string to an int but getting this error.
Unhandled exception. System.FormatException: Input string was not in a correct format.
at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type)
at System.Convert.ToInt32(String value)
at csharpfundamentals.Practice.Main(String[] args)
// Code snippet
Console.WriteLine("Enter a number: ");
string user_input = Console.ReadLine();
int number = Convert.ToInt32(user_input);
Vishal YelvePosted Jul 17, 2022, 1:43 PM
Sachin SinghPosted Jul 16, 2022, 6:11 PM
Uttam KumarPosted Jul 16, 2022, 3:52 PM
Jaydeep PatilPosted Jul 16, 2022, 6:04 AM
Jignesh KumarPosted Jul 16, 2022, 4:20 AM
Hello Curwen,
Please try this one will help you out,
Console.WriteLine("Enter a number: ");
string user_input = Console.ReadLine();
if(!string.IsNullOrEmpty(user_input))
{
int num;
bool isNumeric = int.TryParse(user_input, out num);
if(isNumeric)
{
int number = Convert.ToInt32(user_input);
}
else
{
// Show validation message : string is not valid integer
}