Search code examples
c#console.readline

Exiting 'do while ReadLine' loop not working


I am trying to learn C# as I have little experience there. I wanted to set up a Console.Readline in a Do While loop so I can read in an unknown amount of values into an array. It never exits so the comparison in the while is not working. What is wrong?

do
{
    line = Console.Read();
    if (line != null)
        numbers[c++] = line;
    numbers = new int[c+1];

} while (line != null);

Solution

  • First of all, I would use a List<int> to save the input values. This avoids the necessity to redimension the array, and you could use the list as a normal array.

    Second, there is a lot of difference between the Console.Read and Console.ReadLine. The first returns one by one the character codes of the characters typed and pressing Enter will simply return the character code (13) of the Enter key. To exit the loop you need to press Ctrl + Z that returns -1, not null.

    List<int> numbers = new List<int>();
    int line;
    do
    {
        line = Console.Read();
        if (line != -1)
            numbers.Add(line);
    } while (line != -1);
    for(int x = 0; x < numbers.Count(); x++)
       Console.WriteLine(numbers[x]);
    

    However, this is probably not what you really want. If you need to store the numbers typed as real integer numbers you need code like this:

    List<int> numbers = new List<int>();
    string line = Console.ReadLine();
    int number;
    do
    {
        if(int.TryParse(line, out number))
            numbers.Add(number);
    
    } while (!string.IsNullOrWhiteSpace(line = Console.ReadLine()));
    for(int x = 0; x < numbers.Count(); x++)
       Console.WriteLine(numbers[x]);
    

    In this version I get the line input before entering the loop and then continue until the Enter key is pressed. In every loop I try to convert the input to a valid integer number.

    Note also the usage of TryParse to convert the string to an integer. If your user types something like "abcdef" the TryParse will return false without throwing an exception.

    (Thanks @Patrick for its suggestion.)