Reading from multiple .txt files.

Hi guys! I need help on how to transform my code from reading from a .txt file into a matrix, to choosing what file to read, a similar file but with a different name. I really hope you could help.
Her's the code I have.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
  void CBoard_HelpMeOut::LoadLevel(void)
{
	ifstream gamefile ("tab1.txt");
	if(gamefile.is_open())
		{
			gamefile >> m_nRows >> m_nColumns; 
			for(int row=0; row<m_nRows; row++)       
				for(int col=0; col<m_nColumns; col++)
					{
					gamefile >> m_arrBoard[row][col];    
					}
		}
		else cout << "File does not exist." << endl;
}
Last edited on
The problem is in line 7 to 11. I don't recommend using 2D data structures, for example: std::vector<std::vector<int>>, because there is quite an overhead.

Use a 1 dimensional data structure.

Determine the dimensions of the matrix and then put them in data members such as int dim1 and int dim2.

Then to access elements just use m_arrBoard[i * dim2 + j] where i is the row you want to be on, dim2 is the total number of columns, and j is the column you want to be on.

You can define a range checked function index(int i, int j) that returns i * dim2 + j and access elements like this m_arrBoard[index(5, 5)]

Then to get data from a file to fill your m_arrBoard you just load it regularly.

Example:

1
2
3
4
5
for(int i = 0; i < m_arrBoard.size(); ++i)
{
	gamefile >> temp;
	m_arrBoard[i] = temp;
}


or use the less verbose version

 
std::copy(std::istream_iterator<T>(gamefile), std::istream_iterator(), m_arrBoard.begin());


If you really insist on using a 2D data structure see the Boost Multidimensional Array Library.
Last edited on
Thanks but the problem is no that. The code I have works just fine but for only one file not for multiple files. Do I have to make different functions for each one?
From the code I have seen so far, if you want to load a different level and if the process for loading it is the same you can have 1 function and pass the file name as an argument whenever you call the function.
Last edited on
Could you give me a prototype on how to do that. I'm really a beginner here. The argument part... Thanks.
1
2
3
4
5
void CBoard_HelpMeOut::LoadLevel(const std::string& arg_fn)
{
	std::ifstream gamefile(arg_fn);
	// ...
}
Last edited on
Thanks for that I will try it!
Topic archived. No new replies allowed.