c++ 11 regex_iterator not dereferencable

Hi, I am trying to learn how to use c++ 11 regex and am getting a runtime error of "regex_iterator not dereferencable"

Here is the code. I have narrowed it down to lines 16 - 24. But cannot see how I am making a mistake. Any help would be much appreciated.

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
void cSettings::Parser() {
	std::ifstream file(fname.c_str());

	while(file.is_open() && !file.eof()) {
		
		//read a line from the file
		std::string line;
		std::getline(file,line);

		//creating the regex expression used to draw out the value and key
		std::regex regx(":?[A-z0-9#][A-z0-9.]");
		std::regex_iterator<std::string::iterator> it (line.begin(), line.end(), regx);
		std::regex_iterator<std::string::iterator> iend;


		if (it->str()[0] != '#') {
			
			std::string key = it->str();
			++it;
			//convert second match to float
			std::stringstream ss(it->str());
			float val = 0; 
			ss >> val;
			values[key] = val;
		}


	}

	file.close();
}


An example input file:

1
2
3
4
5
6
7
8
9
#Graphic settigns

bloom = 3.56
anti_aliasing = 1
texture_quality = 3

#Audio settings

#Keybind settings 
First of all, "while(!file.eof()) " is wrong, use while(getline(file, line)).

Now, step through your program and look at what your regex is matching

At line #1, it's matching "#G", leaving "raphic settigns" as the suffix
the first char of the match is #, so you continue, this is fine

at line #2, it's offered an empty string, so it leaves the match results empty (with it->size() == 0).
You're then accessing the empty match out of bounds with it->str()[0]. I don't know for sure if this is when you got your runtime error - sounds like you have Visual Studio, which I can't reach right now, but it is an error in any case.

Now if you fix that, you come to line #3, where your regex matches "bl", leaving "oom = 3.56" as the suffix.

you're storing "bl" as your key and advancing the iterator, which proceeds to execute the next search, where it matches "oo", leaving "m = 3.56" as the suffix.

"oo" of course cannot be stored in a float, and your val is zero.

If I were you, I'd have used a different regex, with two capture groups, one to capture the key and another to capture the value. No iterators, no hassle.
Last edited on
Thanks :) that's done it
Topic archived. No new replies allowed.