10

入力行数が不明です。各行が整数であることはわかっているので、すべての行を含む配列を作成する必要があります。次に例を示します。

入力:

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

3 に答える 3

18
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]);
}
于 2012-04-29T22:12:19.667 に答える
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);
于 2012-04-29T22:25:53.147 に答える