I wrote this code in order to open a text file in a C# language Each line in the file contains five digits such as
0 0 2 3 6
0 1 4 4 7
0 2 6 9 9
1 0 8 11 9
1 1 12 15 11
2 2 12 17 15
The distance between the number and the other is one tab The problem is when you execute the program this error appears
input string was not in correct format in Convert.ToInt32(t[j])
code:
string[] st = File.ReadAllLines("C:\\testing\\result.txt");
int[,] tmp = new int[st.Length - 1, 5];
for (int i = 1; i < st.Length; i++)
{
string[] t = st[i].Split(new char[] { ' ' });
int cnt = 0;
for (int k = 0; k < t.Length; k++)
if (t[k] != "")
{ t[cnt] = t[k]; cnt++; }
for (int j = 0; j < 5; j++)
tmp[i - 1, j] = Convert.ToInt32(t[j]);
}
How can i correct that?
I suggest changing the collection type from 2d array int[,]
into jagged one int[][]
and then use Linq:
using System.Linq;
...
int[][] data = File
.ReadLines(@"C:\testing\result.txt")
.Select(line => line
// Uncomment this if you have empty lines to filter out:
// .Where(line => !string.IsNullOrWhiteSpace(line))
.Split(new char[] {'\t'}, StringSplitOptions.RemoveEmptyEntries)
.Select(item => int.Parse(item))
.ToArray())
.ToArray();
split char
should be a tab character '\t'
instead of single space
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With