C# Read int numbers to array

893 views Asked by At
using System;
using System.IO;

namespace Sudoku
{
    class Game
    {
        private int[,] puzzle = new int[9, 9];

        public void saveToFile()
        {
            StreamWriter str = new StreamWriter("SUDOKU.txt");
            for (int i = 0; i < 9; ++i)
            {
                for (int j = 0; j < 9; ++j)
                {
                    str.Write(puzzle[i, j] + " ");
                }
                str.Write("\t\n");
            }
            str.Close();
        }

        public void readFromFile()
        {
            clear();
            StreamReader str = new StreamReader("SUDOKU.txt");
            for (int i = 0; i < 9; ++i)
            {
                for (int j = 0; j < 9; ++j)
                {
                    puzzle[i, j] = Convert.ToInt32(str.Read());
                }
            }
            str.Close();
        }
    }
}

I can not download the data from the file. Saving works fine and has a view of the txt file:

1 2 3 4 5 6 7 8 9 
4 5 6 7 8 9 1 2 3 
7 8 9 1 2 3 4 5 6 
2 1 4 3 6 5 8 9 7 
3 6 5 8 9 7 2 1 4 
8 9 7 2 1 4 3 6 5 
5 3 1 6 4 2 9 7 8 
6 4 2 9 7 8 5 3 1 
9 7 8 5 3 1 6 4 2 

How it all written in my array 9x9 skipping all the gaps that would be all the data is written correctly?

1

There are 1 answers

0
grovesNL On BEST ANSWER

Instead of using str.Read() which would require you to read single characters (or a buffer that you specified), try using str.Readline() to read a single line for each iteration of i.

public void readFromFile()
{
    StreamReader str = new StreamReader("SUDOKU.txt");
    for (int i = 0; i < 9; ++i)
    {
        string[] lineNumbers = str.ReadLine().Split(' ');
        for (int j = 0; j < 9; ++j)
        {
            puzzle[i, j] = Convert.ToInt32(lineNumbers[j]);
        }
    }
    str.Close();
}

This reads a single line at a time (each iteration of i), splits the line into lineNumbers by separating the current line by space characters. Each number on the current line can then be accessed by lineNumbers[j] within your inner loop (each iteration of j).