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?

4
  • 2
    use resiziable collection - List<int> Commented Aug 1, 2012 at 10:44
  • The answer is to use a collection as turbanoff said. Take a look at a topic that is the same as yours link Commented Aug 1, 2012 at 10:46
  • 2
    @O.D So what? I'm even below that. Commented Aug 1, 2012 at 10:50
  • @CodesInChaos its nothing i would be proud of. Commented Aug 1, 2012 at 11:54

4 Answers 4

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
Sign up to request clarification or add additional context in comments.

1 Comment

Sry, had to wait 5 mins until i could accept it and had to leave.
3
var numbers = new List<int>();
string s;
while(!string.IsNullOrEmpty(s = Console.ReadLine())) {
    numbers.Add(int.Parse(s));
}

2 Comments

Depending on what error behavior is desired, it might also be a good idea to replace int.Parse with int.TryParse.
you can convert it to an array if thats what you really need: ` int[] array = numbers.ToArray();`
0

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

1 Comment

This doesn't actually resize the array. It creates a new array with the desired size, and copies over the existing elements.
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]);  
}

1 Comment

You only answered half the question. You totally missed the stop when the input is empty part.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.