Read the undefined number of lines from standard input

I have an unknown number of input lines. I know that each line is an integer, and I need to create 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 code below, but I can’t get all the lines, and I can’t debug the code because I need to send it to check 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));
}
+5
source share
2 answers
List<int> input = new List<int>();

// first read input till there are nonempty items, means they are not null and not ""
// also add read item to list do not need to read it again    
string line;
while ((line = Console.ReadLine()) != null && line != "") {
     input.Add(int.Parse(line));
}

// there is no need to use ElementAt in C# lists, you can simply access them by 
// their index in O(1):
StockItem[] stock = new StockItem[input.Count];
for (int i = 0; i < stock.Length; i++) {
    stock[i] = new StockItem(input[i]);
}
+11
source

Do you really need identifiers in an array? I would probably try something like this:

    // Use a function that takes a StringReader as an input.
    // That way you can supply test data without using the Console class.
    static StockItem[] ReadItems(StringReader input)
    {
      var stock = new List<StockItem>();

      // Only call ReadLine once per iteration of the loop.
      // I expect this is why you're not getting all the data.
      string line = input.ReadLine();
      while( ! string.IsNullOrEmpty(line) ) {

        int id;
        // Use int.TryParse so you can deal with bad data.
        if( int.TryParse(line, out id) ) { 
          stock.Add(new Stock(id));
        }

        line = input.ReadLine();
      }

      // No need to build an populate an array yourself. 
      // There a linq function for that.
      return stock.ToArray();
    }

Then you can call it with

  var stock = ReadItems(Console.In);
+2
source

All Articles