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
  • 103,479
  • 23
  • 206
  • 257
robertpas
  • 631
  • 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
  • 413,451
  • 75
  • 717
  • 787
  • @robertpas then you should [accept it as the answer](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) – dtsg Aug 01 '12 at 11:03
  • Sry, had to wait 5 mins until i could accept it and had to leave. – robertpas Aug 01 '12 at 11:26
3
var numbers = new List<int>();
string s;
while(!string.IsNullOrEmpty(s = Console.ReadLine())) {
    numbers.Add(int.Parse(s));
}
Marc Gravell
  • 976,458
  • 251
  • 2,474
  • 2,830
  • 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,189
  • 7
  • 48
  • 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
  • 64,877
  • 28
  • 152
  • 226