std::out_of_range, please look!

Hey everyone,

I'm programming a game in c++ and i'm currently working on the file loader,but i've run into a bit of a problem. VC++ 2010 express is my IDE.

FYI the code returns true, the program executes flawless when i comment it out,
Breakpoints say it fails on the if((line[i].at(1) == '.') && (line[1] == ".4a4566696cc81c6053ec708975767498")) and the main function is left out for simplicity, it give's the error :

'exception at 0x74c8b9bc in SSC.exe: Microsoft C++ exception: std::out_of_range at location 0x001df404..

Thanks in advance!
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
bool loadStuff()
{
	//object temp;
	int i;					          
	std::string templine;
	std::string path = "C:/Users/user/Desktop/GameData/data.txt";
	std::vector<std::string> line;
	std::ifstream myfile(path);
	if (myfile.is_open())
	{
		   while(myfile.good() == true){
				if(myfile.good())
				{
					getline (myfile,templine);
					line.push_back (templine);
				}}
				myfile.close();
	}
  	else if(!myfile.is_open()){std::cerr << "failure to open file" << std::endl; exit(-1);}
	int j=line.size();
    for(i=0;i<j;i++){
		if((line[i].at(1) == '.') && (line[1] == ".4a4566696cc81c6053ec708975767498"))
		{
		std::cout << "win" << std::endl; exit(-10);
		}}
	return true;
}
if((line[i].at(1) == '.')
What if line[i] is empty? How can the computer access the element at(1) if it doesn't exist?
As I'm here, I think you are overcomplicating this a little bit:
1
2
3
4
5
6
7
8
9
10
11
12
	std::ifstream myfile(path);
	if (myfile.is_open())
	{
		   while(myfile.good() == true){
				if(myfile.good())
				{
					getline (myfile,templine);
					line.push_back (templine);
				}}
				myfile.close();
	}
  	else if(!myfile.is_open()){std::cerr << "failure to open file" << std::endl; exit(-1);}

Furthermore, for all your checking, you do not check if the statement that actually reads in the data succeeds or fails. After you do getline (myfile,templine); you simply store that data without knowing if it is real data or if the file ended leaving you with nothing.

I would recommend something a little more like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
	std::ifstream myfile(path);
	
	if(!myfile.is_open())
	{
		std::cerr << "Failure to open file: " << path << std::endl;
		exit(-1);
	}
	
	while(std::getline(myfile, templine)) // only execute the body if the read is a success
	{
		line.push_back(templine);
	}

	myfile.close();

That does pretty much the same as your code with more error checking.
Thanks man, thanks to you I found the problem, In the file format I forgot the ''.''
I suddenly realized the drawback of my design thanks to your first comment!

I'll mark it as solved now!
Last edited on
Topic archived. No new replies allowed.