2013-04-01 2 views
0

텍스트 파일을 2 차원 배열로 읽으려고합니다. 그러나 나는텍스트 파일을 2 차원 배열로 읽을 때 올바른 형식이 아닌 입력 문자열

의 오류가 발생합니다. 입력 문자열의 형식이 올바르지 않습니다.

나는 텍스트 파일을 검사했으며 이것이 모두 있어야하며이 오류의 원인을 알 수 없습니까?

 int[,] numberMatrix = new int[10, 10]; 
     string[] split = null; 

     for (int rowCount = 1; rowCount < 11; rowCount++) 
     { 
      int[] temp1DArray = new int[10]; 
      string fileLocation = "C:\\Week10\\one.txt"; 
      string textFile = File.ReadAllText(fileLocation); 

      for (int columnCount = 1; columnCount < 11; columnCount++) 
      { 
       string delimStr = " "; 
       char[] delimiter = delimStr.ToCharArray(); 
       //string fileLocation = "C:\\Week10\\1-100.txt"; 
       //string textFile = File.ReadAllLines(fileLocation); 
       for (int x = 0; x <= 10; x++) 
       { 
        split = textFile.Split(delimiter, x); 
       } 
      } 

      for (int rowCount1 = 1; rowCount1 < 11; rowCount1++) 
      { 
       for (int columnCount = 1; columnCount < 11; columnCount++) 
       { 
        numberMatrix[rowCount1 - 1, columnCount - 1] =Convert.ToInt32(split.ElementAt(columnCount - 1)); 
       } 
      } 
     } 

     for (int rowCount = 10; rowCount > 0; rowCount--) 
     { 
      for (int columnCount = 10; columnCount > 0; columnCount--) 
      { 
       Console.WriteLine(numberMatrix[rowCount - 1, columnCount - 1]); 
      } 
     } 
    } 
+0

오류가 40 행에 있음을 나타냅니다. – ProgrammingRookie

+0

어느 것이 40 행입니까? :) –

+0

파일 내용 및 예상 결과의 예제를 제공하십시오. –

답변

0

그래, 파일 내용과 정확한 예외 설명을 제공하지 않았으므로 가능한 이유가있을 수 있습니다. 나는 파일 파싱을 훨씬 더 단순하게 구현할 수있다.

1 10 20 30 
4234 35 123 543 
42 54 345 645 

: 나는 마술 파일에 하나 개의 번호가 파일에 대해 int

string[] lines = File.ReadAllLines(@"C:\temp\1.txt"); 
var options = StringSplitOptions.RemoveEmptyEntries; 

int[][] numbers = lines.Select(line => line.Split(new[]{' '}, options) 
              .Select(int.Parse) 
              .ToArray()) 
         .ToArray(); 

Console.WriteLine(string.Join(Environment.NewLine, 
           numbers.Select(n => string.Join(" ", n)))); 

에 구문 분석 할 수없는 이유의 이유를 찾을 수있는 답변 생각할 수 없다 인쇄물 :

1 10 20 30 
4234 35 123 543 
42 54 345 645 

사각형 배열 int[,]을 사용하려면 다음을 사용하십시오. c 그것을 해석 할 ode.

int [,] numbersRect = new int[numbers.Length, numbers[0].Length]; 

for (int i = 0; i < numbersRect.GetLength(0); i++) 
{ 
    for (int j = 0; j < numbersRect.GetLength(1); j++) 
    { 
     numbersRect[i,j] = numbers[i][j]; 
    } 
} 
+0

건배 나는 당신의 코드와 위대한을 달렸다. 중첩 루프에 문제가 있음을 의미해야합니다. 그러나 귀하의 코드가 훨씬 간단하다는 데 동의해야합니다. – ProgrammingRookie

-1

여기서부터 split은 서있는 배열을 반환합니다. 그리고 numberMatrix [rowCount1 - 1, columnCount - 1]은 배열 요소이며 배열 자체는 아닙니다. 그래서 numberMatrix [rowCount1 - 1, columnCount - 1] = Convert.ToInt32 (split.ElementAt (columnCount - 1)); 예외가 발생합니다. Convert.ToInt32는 배열이 아닌 단일 값을 사용합니다.

관련 문제