hello, I am trying to read data from a file and store it in a 2-d dynamically allocated array of pointers. I am able to open the file and read the data in but it doesn't account for the end of the line and if I output the data to the screen as I'm reading it in the program will crash when i run it. Also, I want to store each line of data in each row of the array but it doesn't store it line by line. Can anyone help me out?

Here is my code:

void BST_Checker::GenerateDictionary(int size)
{
	cout << size << endl;	
	node_length = 30;
	int check;
	dictionary = new char*[size];
	for(int i = 0; i < node_length; i++)
	{
		dictionary[i] = new char[node_length];
	}

		 ifstream inFile;
	
	 //instruction to open a file named "dictionary_1.txt"
	 inFile.open("dictionary_1.txt");
	 if (!inFile){
		 cout << "Can't open file!." << endl;
		 exit(1);
	 }
	
	for(int n = 0; n < size; n++)
	{
		for(int m = 0; m < node_length; m++)
		{
		inFile >> dictionary[n][m];
		cout << dictionary[n][m];
		}
		cout << endl;
	}

I just posted the method that reads the data from the file. I have another area of the program that opens the file and counts each row of data and sets the "size" variable that is passed here. Also, node_length is supposed to set the number of columns in the array and it is declared as a private variable in the class that this method is a part of. The dictionary file that is being read is in a format where you have one word on each line, such as:

bark
boy
cat
turtle

Thanks in advance for the help!

do you have to use a 2d char array? i would think it would be easier to use a string and vector and use the getline methode to extract from the file. something like

vector<string> dictionary;
string temp;
while (getline(inFile, temp))
       dictionary.push_back(temp);

Edited 6 Years Ago by NathanOliver: n/a

do you have to use a 2d char array? i would think it would be easier to use a string and vector and use the getline methode to extract from the file. something like

vector<string> dictionary;
string temp;
while (getline(inFile, temp))
       dictionary.push_back(temp);

Using a 2-d array isn't a requirement. However, I'm not familiar with vectors and I am planning on using the data in the array to compare, row by row, with another 2-d array created elsewhere. This is to see if they have a row that contains the same information (ie, a match). Is there a way to compare a string stored in a vector to a row of chars in a 2-d array?

This article has been dead for over six months. Start a new discussion instead.