c# - Input string not in the correct format when reading a text file into a 2d Array -
i trying read text file 2d array. error of
input string not in correct format.
i have checked text file , should , cant see why error happening?
int[,] numbermatrix = new int[10, 10]; string[] split = null; (int rowcount = 1; rowcount < 11; rowcount++) { int[] temp1darray = new int[10]; string filelocation = "c:\\week10\\one.txt"; string textfile = file.readalltext(filelocation); (int columncount = 1; columncount < 11; columncount++) { string delimstr = " "; char[] delimiter = delimstr.tochararray(); //string filelocation = "c:\\week10\\1-100.txt"; //string textfile = file.readalllines(filelocation); (int x = 0; x <= 10; x++) { split = textfile.split(delimiter, x); } } (int rowcount1 = 1; rowcount1 < 11; rowcount1++) { (int columncount = 1; columncount < 11; columncount++) { numbermatrix[rowcount1 - 1, columncount - 1] =convert.toint32(split.elementat(columncount - 1)); } } } (int rowcount = 10; rowcount > 0; rowcount--) { (int columncount = 10; columncount > 0; columncount--) { console.writeline(numbermatrix[rowcount - 1, columncount - 1]); } } }
so ok, haven't provided file contents , exact exception description (it can fire on reason possible). can give more simple implementation file parsing. can't think of answer, magically find reason of why 1 number in file can't parsed 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))));
for file:
1 10 20 30 4234 35 123 543 42 54 345 645
prints:
1 10 20 30 4234 35 123 543 42 54 345 645
if need rectangle array int[,]
use next code parse to.
int [,] numbersrect = new int[numbers.length, numbers[0].length]; (int = 0; < numbersrect.getlength(0); i++) { (int j = 0; j < numbersrect.getlength(1); j++) { numbersrect[i,j] = numbers[i][j]; } }
Comments
Post a Comment