2012-04-29 11 views
5

入力行数が不明です。私は、各行が整数であることを知っている、と私は、たとえば、すべての行と列を作成する必要があります。標準入力から定義されていない行数を読み取る

入力:

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

でそれを呼び出すことができます

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

:私はおそらくこのような何かをしようとするだろうhttp://www.linqpad.net/ –

+0

私はそれが見えなかった、申し訳ありません私のスペルチェッカーはスペイン語に設定され、すべての私のテキストは、赤いマーカーで、それについて残念です。 – Santanor

+1

入力を提供する必要がある場合は、[Ideone](http://ideone.com)も便利です。 – Ryan

答えて

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

'while(!string.IsNullOrEmpty(line = Console.ReadLine()))'はもっとよかったでしょう:) – Ryan

+0

@minitech、はい、私はあなたが書いた方法で書くと思っていましたが、ちょっと混乱します。 –

+1

問題はsintaxisではない、私はC#で始まっていないが、なぜこのソリューションが動作しないのか分からない(いいえ、あなたの解決策はどちらもうまくいきませんでした):(私は探し続けるつもりですそれで、ありがとう!! – Santanor

2

あなたが実際には配列内のIDが必要ですか?そして、あなたは、VSなしで簡単にコンパイルして、擬似デバッグすることができ、Linqpad試してみて

var stock = ReadItems(Console.In); 
関連する問題