Page 1 of 1

Error with File Loading

Posted: Thu Dec 31, 2009 1:42 pm
by lotios611
Well, I was just screwing around with file loading, and this weird bug happened. I've fixed the bug, but I just wanted to post what happened.

Here's main.cpp:

Code: Select all

#include <string>
#include <fstream>
#include <iostream>

int main()
{
	std::string temp[5];
	int i = 0;
	std::fstream file;
	file.open("Dictionary.txt");
	if (file.is_open())
	{
		while (!file.eof())
		{
			std::getline(file, temp[i++]);
			std::cout << temp[i++] << std::endl;
		}
		file.close();
	}
	else
	{
		std::cout << "Unable to load file";
	}
	return 0;
}
And here's Dictionary.txt:

Code: Select all

Hello - A word
Testing - Testing
APPLES - ANOTHER WORD
banana - a fruit 

Re: Error with File Loading

Posted: Thu Dec 31, 2009 1:51 pm
by dani93
Your loop is wrong. It should be:

Code: Select all

for (int i = 0; !file.eof(); i++)
{
  std::getline(file, temp[i]);
  std::cout << temp[i] << std::endl;
}
You got a too high index cause you incremented "i" wrong -> segmentation fault

Re: Error with File Loading

Posted: Thu Dec 31, 2009 2:00 pm
by lotios611
Like I said, I already fixed it. So that's what a segmentation fault is...

Re: Error with File Loading

Posted: Thu Dec 31, 2009 4:04 pm
by short
lotios611 wrote:Like I said, I already fixed it. So that's what a segmentation fault is...
Segment faults (on the low level) happen when you try and de-reference an invalid pointer. Since arrays are after all pointers, when you try to index that is larger then you declared your array size to be, you are indeed de-referencing an invalid pointer. :)

Re: Error with File Loading

Posted: Fri Jan 01, 2010 9:03 am
by lotios611
I actually never bothered to look "Segmentation fault" up. You learn something new every day.