Reading data from a file

Hey there,

I'm trying to load in data from an external file for processing. But I'm having some trouble. I've been googling for some time but I'm not coming closer to getting my function to work.

As an example, here are a few lines from the file:


1
2
3
4
5
6
7
8
9
FFFF00FF$
FFFFEB00$
FFFFC200$
FFFF00FF$
FF561F04$
FFE86307$
FFFFF700$
FFFFDD00$
FFFFA100$


I need to read all the data per line, I'm using the '$' as a delimiter.

I'm trying to get the data as an string and then store it an in const char* array with the .c_str() function.

My function currently 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
25
26
27
28
29
30
31
32
33
34
35
36
37
Surface::Surface(std::string a_File, float a_X, float a_Y, float a_Width, float a_Height){
	m_X = a_X;
	m_Y = a_Y;
	m_Width = a_Width;
	m_Height = a_Height;

	FlushImageData();

	int m_FileWidth = 0;
	int m_FileHeight = 0;
	int m_FileStream = a_Height * a_Width;
	int m_Stream = 0;

	std::ifstream m_File(a_File.c_str());
	if(!m_File.is_open()){
		MessageBox(NULL, DISCO_ERR_15, DISCO_2D_RESOURCE_ERROR, MB_OK | MB_ICONEXCLAMATION);
		exit(0);
	}
	std::string m_Line;
	while(m_Stream < m_FileStream){
		std::stringstream linestream(m_Line);
		std::string m_Data;
		std::getline(linestream, m_Data, '$');

		m_ImageData[m_FileHeight][m_FileWidth] = m_Data.c_str();

		m_FileWidth++;
		if(m_FileWidth > (int)a_Width){
			m_FileWidth = 0;
			m_FileHeight++;
		}
		m_Stream++;
	}
	m_File.close();

	m_IsImage = true;
}


If I insert a break point at the line where it should be storing the data in m_ImageData, the m_Data.c_str() shows up empty and the m_ImagaDate itself show either a 0 or a bad_ptr.

Any ideas on how to fix this, or can anyone spot a mistake I am making?

In addition, at the moment I'm looping through the file with the while(m_Stream < m_FileStream). Before I tried while(std::getline(file, line)){ but when I tried to use that it simply skipped the entire loop.

To sum it all up, the file holds different color codes. I'm trying to store these codes in to an array so that they are store as a whole, like they are in the file. i.e.:

m_ImageData[0][0] = "0xFFFF00FF"
etc.

If you need any additional information please let me know!

Thanks in advance!
Last edited on
You're not actually using m_File for anything. You open on 14, check that it's open on 15, then you only use it again on 34 to close it. You probably ought to be passing it as the first parameter to std::getline() on 23.
Thanks for your reply!

Hmm yes sounds logical, this is the first time I'm really trying to do something with reading data from a file. I'll look in to it as soon as I have the possibility.

Edit:

You were totally right, I removed the linestream part and replaced linestream by m_File in the getline function, it now loads in the appropriate data.

Thanks again!
Last edited on
Topic archived. No new replies allowed.