2012-04-29 21 views
5

Tengo un número desconocido de líneas de entrada. Sé que cada línea es un entero, y necesito hacer una matriz con todas las líneas, por ejemplo:Lee un número indefinido de líneas desde la entrada estándar

de entrada:

12 
1 
3 
4 
5 

y necesito conseguirlo como una matriz: {12,1,3,4,5}

Tengo el siguiente código, pero no puedo obtener todas las líneas, y no puedo depurar el código porque tengo que enviarlo para probarlo.

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

Dar LINQPad una oportunidad, puede compilar y pseudo-depuración fácilmente sin VS. http://www.linqpad.net/ –

+0

Lo siento, no lo vi, mi corrector ortográfico está configurado en español y todo mi texto está con el marcador rojo, lo siento. – Santanor

+1

[Ideone] (http://ideone.com) también es bueno si necesita proporcionar información. – Ryan

Respuesta

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()))' se vería mejor :) – Ryan

+0

@minitech, sí, al principio pensé en escribirlo de la forma en que escribiste, pero después de eso pensé que podría ser un poco confuso –

+1

El problema no es el sintaxis, no empiezo con C# pero no sé por qué esta solución no funciona (no, su solución tampoco funcionó) :(voy a seguir buscando , gracias! – Santanor

2

es lo que realmente necesitan los identificadores en una matriz? Probablemente probar algo como esto:

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

Entonces se le puede llamar con

var stock = ReadItems(Console.In); 
Cuestiones relacionadas