Introduction
This tutorial will teach us how to read a text file into a 2D array in C. We will be using the fgetc() function to read each character one by one from the text file and then store it in a 2D character array.
Creating a 2D Array
Creating a 2D array in C can be done in multiple ways. The most common way is to create an array of pointers, where each pointer points to an array that contains the data. Another way is to create a single array that contains all the data.
Declaring a 2D Array
C does not allow for variable-sized arrays, so you will need to specify how many rows and columns your array will have. To declare a 2D array in C, first enter the data type (of the elements that will go in your array) followed by the dimensions. For example:
int myarray[3][4];
This declares a 3 row, 4 column 2D array of type int. The following code fills this 2D array with increasing numbers starting from 0. Note that when you use this method of filling a 2D array with values, the first index is always for the rows and the second is for the columns:
“`
include // necessary for printf()
int main()
{
int myarray[3][4]; // create 3 row, 4 column int array
// fill with increasing numbers starting from 0
for (int i=0; i<3; i++) { // loop through rows
for (int j=0; j<4; j++) { // loop through columns
myarray[i][j] = i*4 + j; // assign value to each element
}
}
printf("2D Array\n"); // display heading before elements are shown
printf("--------------------\n"); // visual aid border between heading and elements
for (int i=0; i<3; i++) { // loop through rows again
for (int j=0; j<4; j++) { // loop through columns again
printf("%d ", myarray[i][j]); // print each element on same line as its neighbor(s) - no newline character needed at end of line since next iteration will print on next line anyway...or you could add \n character outside nested loop if you prefer! interior of double quotes! - include space after %d format specifier so that consecutive numbers print with space between their digits to improve readability....or include Tab characters '\t' instead if you prefer! ;) Also feel free to use other characters like asterisks '*' or whatever symbol you like as long as it doesn't interfere with reading individual digits within large numbers :P } printf("\n"); outside nested loop - prints newline char here so that output appears in neat rows and columns - also outside nested loop so only executed once per row rather than once per column ;) ---------------------------------------------------------- note that could also put \n char at end of every iteration inside nested loops if want emplty lines between each outputted element - don't forget escape sequence backslash before char n inside double quotes!!!....or empty lines between each row if put \n outside loops entirely ;) */</p><br /><h3>Initializing a 2D Array</h3><br /><p>
There are several ways to initialize a 2D array in C. One way is to use nested for loops to initialize each element individually:
Reading Text Files into a 2D Array
You can read text files into a 2D array in C if the text file contains data that is structured in this way. The fstream library will allow you to open and read the text file. You can then use a for loop to read each line of the text file into a 2D array.
Reading a Text File into a 1D Array
Assuming that the text file is called “input.txt” and looks like this:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
17 18 19 20
21 22 23 24
We can read the whole file into a 1D array like this:
int[] data = File.ReadAllLines(“input.txt”) .SelectMany(s => s.Split(‘ ‘)) .Select(n => Convert.ToInt32(n)) .ToArray();
Reading a Text File into a 2D Array
We can use the StreamReader class to read a text file into a 2D Array. The following code reads the contents of a text file into a 2D Array called arrText. The file has 5 columns and 6 rows. We use the ReadLine() method to read each line of text, and then use the Split() method to split each line into an array of Strings. Finally, we add each line to our 2D Array:
arrText = new string[6,5];
// Read in the file line by line…
StreamReader objReader = new StreamReader(“arrays.txt”);
string sLine = “”;
int iRow = 0;
while (sLine != null)
{
iRow++;
sLine = objReader.ReadLine();
if (sLine != null && !sline.StartsWith("//")) // Ignore comments...
{
// Split the current line into an array of strings...
string[] arrSplit = sLine.Split(' ');
// Add the strings to our 2d Array...
for (int iCol=0; iCol < 5; iCol++)
arrText[iRow,iCol] = arrSplit[iCol];
}
}
// Close the reader...
objReader.Close();
Conclusion
We have come to the end of this tutorial. In this tutorial, we have shown how toread text file into 2d array c. We hope that you have found this tutorial helpful.