Question Input string was not in the correct format

Anonymous

Well-known member
Joined
Sep 29, 2020
Messages
84
Programming Experience
Beginner
I am writing a program to input and output a simple array.

C#:
 static void Main(string[] args)
        {
            int[] arr = new int[10];
            Console.WriteLine("Enter nmber of elements");
            int n = int.Parse(Console.ReadLine());
            Console.WriteLine("Enter the elements");
            for (int i = 0; i < n; i++)
                arr[i] = int.Parse(Console.ReadLine());
            Console.WriteLine("The array is\n");
            for (int j = 0; j < n; j++)
                Console.WriteLine(arr[j] + "\n");
            Console.ReadKey();


        }

But it gives me input string was not in the correct format on
C#:
arr[i] = int.Parse(Console.ReadLine());

I also tried

C#:
arr[i] = Convert.ToInt32(Console.ReadLine());
but same error.
 
Last edited:
You can't convert a string to an int if the characters don't represent a number. Obviously that is the case here. You haven't told us what you actually typed in. It should be obvious that that is important. Whatever it was, it wasn't a number or, at least, not an integral number. If there's a chance that the input may not be valid then you should be validating it. You can validate and convert in one go with int.TryParse. If you don't want to validate then you better be sure that the input will always be valid.
 
Your code doesn't really make sense even apart from that. You create an array with 10 elements and then you ask the user to specify the number of elements. Shouldn't you be asking that question first and then creating an array with that many elements?

Finally, why call Console.WriteLine and tack a line feed on the end of it? There's already a line break appended when you call WriteLine.
 
Back
Top Bottom