Exiting 'do while ReadLine' loop not working

2.8k Views Asked by At

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

There are 2 best solutions below

2
On BEST ANSWER

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

5
On

If you're using Console.Readline() then line will be null if you press Ctrl+Z (as mentioned by @Patrick). You should check for empty string instead:

    do
    {
        line = Console.ReadLine();
        if (line != null)
            numbers[c++] = int.Parse(line); //assigning string to the last element in the array of ints?
            //if you need to parse string to int, use int.Parse() or Convert.ToInt32() 
            //whatever suits your needs
        numbers = new int[c+1];

    } while (!string.IsNullOrEmpty(line));

Anyway, it's not clear what you're trying to accomplish with this code as you're creating new array on every iteration. Moreover, this will not work as you have an array of int but assign a string value to it.