zozo
zozo

Reputation: 85

Convert string from text file to integer array

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?

Upvotes: 4

Views: 425

Answers (3)

Lajos Arpad
Lajos Arpad

Reputation: 76414

You have five numbers per row, but not necessarily five digits. You will need a more complex solution, like this:

string[] st = File.ReadAllLines("C:\\testing\\result.txt");
int[,] tmp = new int[st.Length - 1, 5];
bool isAlreadyNumber = false;
bool isEmptyRow = true;
int rowIndex = -1;
int colIndex = -1;
for (int i = 0; i < st.Length; i++) {
   isAlreadyNumber = false;
   isEmptyRow = true;
   foreach (char c in st[i]) {
      if ((c >= '0') && (c <= '9')) {
          if (isAlreadyNumber) {
              tmp[rowIndex][colIndex] = tmp[rowIndex][colIndex] * 10 + (c - '0');
          } else {
              tmp[rowIndex][colIndex] = c - '0';
              if (isEmptyRow) rowIndex++;
              isEmptyRow = false;
              isAlreadyNumber = true;
          }
      } else {
          isAlreadyNumber = false;
      }
   }
 }

Note, that the indexing was fixed. This untested code handles other separators and empty lines as well, but still assumes there will be five numbers.

Upvotes: 0

Bhuban Shrestha
Bhuban Shrestha

Reputation: 1324

split char should be a tab character '\t' instead of single space

Upvotes: 1

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

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();  

Upvotes: 8

Related Questions