I wish to replace a set of substrings in a string. I have experimented with various methods to do this. I thought I had it working, but no... under certain circumstances that I do not understand but can readily reproduce, my code encounters a runtime error with the message: 'the string iterator is not dereferencable'.

Here's the code I have been trying to develop:
Code:
	int count;
	char buf[256];
	double x[7];
	string s, so, sr;
	string::iterator tt;
	vector<string> vs1, vs2;

	x[0] = 1.123234345;
	x[1] = 2.293849223;
	x[2] = 3.283746834;
	x[3] = 4.758439842;
	x[4] = 5.234543234;
	x[5] = 6.728394823;
	x[6] = 7.923874943;

	s = "t = %0.8f\nu = %0.8f\nv = %0.8f\nw = %0.8f\nx = %0.8f\ny = %0.8f\nz = %0.8f\n";
	cout << s << endl;

		
	so = "%0.8f";
	tt = s.begin();
	count = 0;
	while(tt != s.end())
	{
		if(*tt == '%')
		{
			sprintf(buf, "%0.4f", x[count]);
			//sprintf(buf, "%0.5f", x[count]);	// error: string iterator not dereferencable
			sr = string(buf);
			s.replace(tt, tt + so.size(), sr);
			count++;
		}
		*tt++;
	}

	cout << s << endl;
Now, at first glance, I thought I understood the problem, that is, I thought that the replacement string cannot be longer than the substring one wishes to replace. Thus, so = "%0.8f"; has 5 characters (plus '\0'), so that using a 6 or greater length string will cause the replace function iterator to fail.

But further experimentation shows that this is probably NOT the problem. For example, this code works without a problam
Code:
	size_t n;
	string s, so, sr;
	string::iterator tt;

	s = "x = %0.8f";
	so = "%0.8f";
	sr = "123233453454.345445645645656567";

	cout << s << endl;

	n = s.find('%', 0);
	tt = s.begin() + n;

	s.replace(tt, tt + so.size(), sr);

	cout << s << endl;

// output:   x = 123233453454.345445645645656567
Frankly, I am at a loss to know what's happening here. Any of your ideas would certainly be appreciated. Thanks.

Mike