str_buf.length doesn't reach the end of my loop

Hi,
I am using buf.end. My code inserts a return character \r to a string. It works like it should but it stops before the end of the file. Notice the 300 in the code? That was needed and was just a random number to see if it would solve my issue. x < str_buf.length()+300;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  if (myfile.good()) {
		/*Read data using streambuffer iterators.*/
		vector<char> buf((std::istreambuf_iterator<char>(myfile)), (std::istreambuf_iterator<char>()));

		/*str_buf holds all the data including whitespaces and newline .*/
		string str_buf(buf.begin(), buf.end());

		string str = str_buf;

		for (int x = 0; x < str_buf.length()+300; x++) // Add '\r' to all lines in the loaded text.
		{

			if (str[x] == 0x0A) { str.insert(x, "\r"); x++; }

		}
Last edited on
1
2
3
4
5
6
7
8
using iterator = std::istreambuf_iterator<char> ;
const std::string strbuf{ iterator(myfile), iterator() } ;
std::string str ;
for( char c : strbuf )
{
    if( c == '\n' ) str += '\r' ; // '\n' ;
    str += c ;
}

Last edited on
The issue is the for loop. You are iterating over the length of str_buf but then using x as an index into str which after the first insertion isn't in step with str_buf and is of a greater length.
Thanks JLBorges and seeplus.

@seeplus. Your suggestion makes sense and I added another variable to the for loop (y)l Works perfectly right now.

Thanks so much for your guy's help. thumbs
Solved :)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/*Open the stream in default mode.*/
	std::ifstream myfile(File_Path_Credits);

	int z = 0; // The position in the str buffer

	if (myfile.good()) {
		/*Read data using streambuffer iterators.*/
		vector<char> buf((std::istreambuf_iterator<char>(myfile)), (std::istreambuf_iterator<char>()));

		/*str_buf holds all the data including whitespaces and newline .*/
		string str_buf(buf.begin(), buf.end());

		string str = str_buf;

		for (int x = 0, Y = 0; x < str_buf.length(); x++,Y++) // Add '\r' to all lines in the loaded text.
		{

			if (str[Y] == 0x0A) { str.insert(Y, "\r"); Y++; }

		}
Topic archived. No new replies allowed.