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);

Sachin SinghRank #66 · 26.2K reputationPosted Jul 16, 2022, 2:11 PM EDT
Jignesh KumarRank #91 · 22.9K reputationPosted Jul 16, 2022, 12:20 AM EDT
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
}
Jaydeep PatilRank #205 · 11.7K reputationPosted Jul 16, 2022, 2:04 AM EDT
Uttam KumarRank #1,076 · 1.8K reputationPosted Jul 16, 2022, 11:52 AM EDT
Vishal YelveRank #178 · 13.6K reputationPosted Jul 17, 2022, 9:43 AM EDT