Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read an undefined number of lines from standard input

Tags:

c#

I have an unknown number of lines of input. I know that each line is an integer, and I need to make an array with all the lines, for example:

Input:

12
1
3
4
5

and I need to get it as an array: {12,1,3,4,5}

I have the below code, but I can't get all the lines, and I can't debug the code because I need to send it to test it.

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

string line;
while ((line = Console.ReadLine()) != null) {
     input.Add(int.Parse(Console.In.ReadLine()));
}

StockItem[] stock = new StockItem[input.Count];
for (int i = 0; i < stock.Length; i++) {
    stock[i] = new StockItem(input.ElementAt(i));
}
like image 803
Santanor Avatar asked Apr 29 '12 22:04

Santanor


1 Answers

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

// As long as there are nonempty items read the input
// then add the item to the list    
string line;
while ((line = Console.ReadLine()) != null && line != "") {
     input.Add(int.Parse(line));
}

// To access the list elements simply use the operator [], instead of ElementAt:
StockItem[] stock = new StockItem[input.Count];
for (int i = 0; i < stock.Length; i++) {
    stock[i] = new StockItem(input[i]);
}
like image 133
Saeed Amiri Avatar answered Oct 26 '22 08:10

Saeed Amiri