I am trying to read a text file into a 2d array. However I get an error of
Input string was not in the correct format.
I have checked the text file and it is all as it should be and I cant see why this error is happening?
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]);
}
}
}
So ok, you haven't provided any file contents and exact Exception description (it can fire on any reason possible). I can give much more simple implementation for file parsing. I can't think of an answer, which will magically find the reason of why one number in your file can't be parsed to 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 you need rectangle array int[,]
use next code to parse it to.
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];
}
}
From where I standing split returns an array. And numberMatrix[rowCount1 - 1, columnCount - 1] is array element - not array itself. So numberMatrix[rowCount1 - 1, columnCount - 1] =Convert.ToInt32(split.ElementAt(columnCount - 1)); will fire an exception. Also Convert.ToInt32 takes a single value not an array.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.