Convert string from text file to integer array

I wrote this code to open a text file in C # language. Each line in the file contains five digits, for example

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 that this error appears during program execution.

the input line was not in the correct format in Convert.ToInt32 (t [j])

the 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 fix this?

+4
source share
3 answers

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

+1
source

2d int[,] int[][], 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();  
+8

You have five numbers per line, but not necessarily five digits. You will need a more complex solution, for example:

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;
      }
   }
 }

Please note that indexing has been fixed. This unverified code handles other delimiters and blank lines, but still assumes there will be five numbers.

0
source

Source: https://habr.com/ru/post/1677149/


All Articles