从标准输入读取未定义的行数

时间:2012-04-29 22:05:18

标签: c#

我有一定数量的输入线。我知道每一行都是一个整数,我需要创建一个包含所有行的数组,例如:

输入:

12
1
3
4
5

我需要将其作为数组:{12,1,3,4,5}

我有以下代码,但我无法获得所有代码,而且我无法调试代码,因为我需要发送它来测试它。

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));
}

3 个答案:

答案 0 :(得分:13)

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]);
}

答案 1 :(得分:2)

你真的需要数组中的id吗?我可能会尝试这样的事情:

    // 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's a linq function for that.
      return stock.ToArray();
    }

然后你可以用

来调用它
  var stock = ReadItems(Console.In);

答案 2 :(得分:0)

使用列表是一种很好的方法。但是你应该考虑限制总行数。

此外,OP没有说,空行应该终止列表!

所以应该只检查null。

请参阅How to detect EOF on the console in C#? What does Console.ReadLine() returns upon EOF?