Search code examples
c#tryparse

Int.tryparse, when inout is a string, will still fill up an array slot


So im following a tutorial and I wanted to mess around with the code myself and use a Int.Tryparse instead of a Int.Parse.

It worked but when I enter a character or string it will still fill up a slot in my array as a "0".

Here's my code:

Console.WriteLine("How many employee IDs would you like to register?");



string input = Console.ReadLine();

int length; 

if(int.TryParse(input, out length))
{
    int[] employeeIds = new int[length];

    for (int i = 0; i < length; i++)
    {
        Console.Write("Please enter the employee ID.");
        string input2 = Console.ReadLine();
        int id;
        if(int.TryParse(input2, out id))
        {
            employeeIds[i] = id;
        }
        else
        {
            Console.WriteLine("Invalid input, please enter a valid integer number.");
        }
    }
    for (int i = 0; i < employeeIds.Length; i++)
    {
        Console.WriteLine($"ID {i + 1}:  \t{employeeIds[i]}");
    }
}
else
{
    Console.WriteLine("Input is invalid, please input an integer number.");
}

I would like to learn how to prevent it from filling up an array slot with a 0 and only add to it if the input was valid ( an int).

Any help would be greatly appreciated thank you!


Solution

  • The problem is that when parsing fails (i.e. non-parsable string), the iterator (which represents array position) is incremented to the next value, skipping one array position and leaving the default int value of 0 in the skipped position.

    You need to fix the flow of control so that this doesn't happen. There are many different ways to fix these kinds of issues. You could change employeeIds to List<int> and then use a while loop to continue looping until you have the expected number of values.

    Console.WriteLine("How many employee IDs would you like to register?");
    
    
    
    string input = Console.ReadLine();
    
    int length; 
    
    if(int.TryParse(input, out length))
    {
        List<int> employeeIds = new List<int>(); // ** changed **
    
        while (employeeIds.Count < length) // ** changed **
        {
            Console.Write("Please enter the employee ID.");
            string input2 = Console.ReadLine();
            int id;
            if(int.TryParse(input2, out id))
            {
                employeeIds.Add(id); // ** changed **
            }
            else
            {
                Console.WriteLine("Invalid input, please enter a valid integer number.");
            }
        }
        for (int i = 0; i < employeeIds.Count; i++) // ** changed **
        {
            Console.WriteLine($"ID {i + 1}:  \t{employeeIds[i]}");
        }
    }
    else
    {
        Console.WriteLine("Input is invalid, please input an integer number.");
    }