2013-03-03 3 views
0

J'ai un fichier texte contenant le contenu suivant:entiers lecture d'un fichier texte dans C#

0 12 
1 15 
2 6 
3 4 
4 3 
5 6 
6 12 
7 8 
8 8 
9 9 
10 13 

Il n'y a pas d'espace entre deux lignes, mais il y a un espace entre les deux nombres. Je veux lire ces entiers à partir d'un fichier txt et enregistrer les deux colonnes en deux tableaux différents en C# .cn anyone help

+2

Qu'avez-vous essayé jusqu'à présent? – ronen

Répondre

3

Effectuez les opérations suivantes:

var r = File.ReadAllLines(path) 
      .Select(line => line.Split(' ')) 
      .Select(arr => new 
       { 
        Column0 = Int32.Parse(arr[0]), 
        Column1 = Int32.Parse(arr[1]) 
        // etc 
       }) 
      .ToArray(); 

Puis:

int[] column0 = r.Select(x => x.Column0).ToArray(); // note double loop over r 
int[] column1 = r.Select(x => x.Column1).ToArray(); 

ou plus long, mais aussi plus efficace:

int[] column0 = new int[r.Length], column1 = new int[r.Length]; 

for (int i = 0; i < r.Length; i++) // single loop over r 
{ 
    column0[i] = t[i].Column0; 
    column1[i] = t[i].Column1; 
} 

ou encore plus long, mais aussi (en parlant général) encore plus efficace:

List<int> column0 = new List<int>(), column1 = new List<int>(); 

using (Stream stream = File.Open(path, FileMode.Open)) 
using (TextReader sr = new StreamReader(stream, Encoding.UTF8)) 
{ 
    string line; 
    while ((line = sr.ReadLine()) != null) 
    { 
     string[] arr = line.Split(' '); 
     column0.Add(Int32.Parse(arr[0]); 
     column1.Add(Int32.Parse(arr[1]); 
    } 
} 

Pour itérer/Résultat d'affichage (zéro à base d'index, à savoir la ligne 0, 1, etc.):

for (int i = 0; i < column0.Length; i++) 
{ 
    Console.WriteLine("Line {0}: column 0: {1}, column 1: {2}", i, column0[i], column1[i]); 
} 

Pour une meilleure fiabilité, utilisez une fonction au lieu de Int32.Parse:

static int Parse(string input) 
{ 
    int i; 
    if (!Int32.TryParse(intput, out i) 
     throw new Exception("Can't parse " + input); 
    return i; 
} 
+0

J'ai essayé d'utiliser le code ci-dessus mais cela soulève une erreur en disant "La chaîne d'entrée n'était pas dans un format correct" quand j'affiche le tableau. –

+0

Comment puis-je afficher les valeurs de tableau? –

+0

@Naman: Erreur signifie que la ligne à diviser ne peut pas être analysée comme int. Gauche pour espacer partie ou droite. Le fichier ne contient-il pas de décimales (avec un point décimal, etc.)? – abatishchev

0

Vous pouvez vérifier les fol code bas ainsi ..

string data = string.Empty; 
     List<int[]> intarray = new List<int[]>(); 

     void ReadData() 
     { 
      data = File.ReadAllText("Input.txt"); 
     } 
     List<int[]> Getdata() 
     {    
      string[] lines = data.Split('\n', '\r'); 
      foreach (string line in lines) 
      { 
       if(!string.IsNullOrEmpty(line.Trim())) 
       { 
        int[] intdata = new int[2]; 
        string[] d = line.Split(' '); 
        intdata[0] = Convert.ToInt32(d[0]); 
        intdata[1] = Convert.ToInt32(d[1]); 
        intarray.Add(intdata); 
        intdata = null; 
       } 
      } 

      return intarray; 
     }