0

I want to add multiple values into an array, but I want to stop when I feel like it.

Here is the condition I added

while (numbers[i] != 10)
{
    i++;
    numbers[i] = int.Parse(Console.ReadLine());
    Console.WriteLine(numbers[i]);
}

It will stop when the value entered is 10. But I want it to stop when I just press ENTER.

How do I do this?

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
robertpas
  • 643
  • 5
  • 12
  • 25

4 Answers4

4

If you are asking about how to detect the "just press ENTER" condition:

var input = Console.ReadLine();
if (input == "") {
    break;
}

numbers[i] = int.Parse(input);
// etc
Jon
  • 428,835
  • 81
  • 738
  • 806
3
var numbers = new List<int>();
string s;
while(!string.IsNullOrEmpty(s = Console.ReadLine())) {
    numbers.Add(int.Parse(s));
}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • Depending on what error behavior is desired, it might also be a good idea to replace `int.Parse` with `int.TryParse`. – CodesInChaos Aug 01 '12 at 10:50
  • 1
    you can convert it to an array if thats what you really need: ` int[] array = numbers.ToArray();` – Obaid Aug 01 '12 at 10:50
0

I guess you are looking for some way to re-size the array, you can use Array.Resize

Vamsi
  • 4,237
  • 7
  • 49
  • 74
  • 1
    This doesn't actually resize the array. It creates a new array with the desired size, and copies over the existing elements. – CodesInChaos Aug 01 '12 at 10:51
0

Declare numbers like this.

List<int> numbers = new List<int>();

Then modify the loop as such.

while (numbers[i] != 10)
{
    i++;

    string input = Console.ReadLine();
    if (string.IsNullOrEmpty(input)) { break; }

    numbers.Add(int.Parse(input));
    Console.WriteLine(numbers[i]);  
}
Mike Perrenoud
  • 66,820
  • 29
  • 157
  • 232