Strings

When I run my code with the input "<b>this should be bold</b>asdf<head>inception of<head>this should be deleted</head>pooooop</head>asdf", it places an * between the l and the d, like so bol*d</b>. However, I'm not sure why. This code "std:: size_t end_bold = input.find ("</b>");" is finding the correct index of the string. But places the * in the wrong place. Any suggestions?

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#include <string>
#include <vector>

//"<b>this should be bold</b>asdf<head>inception of<head>this should be deleted</head>pooooop</head>asdf";

int main ()
{	
	std::string input; 
	getline (std::cin, input);
	std::size_t start_head = input.rfind ("<head>"); 
	std::size_t end_head = input.find ("</head>"); 

	while (start_head == std::string::npos && end_head == std::string::npos)
	{
		getline (std::cin, input);
		start_head = input.rfind ("<head>"); 
		end_head = input.find ("</head>"); 
	}

	while (input.find ("<head>") != std::string::npos && input.find ("<head>") != std::string::npos)
	{
		start_head = input.rfind ("<head>"); 
		end_head = input.find ("</head>"); 
		
		start_head; 
		end_head = end_head - start_head + 7; 

		input.erase (start_head, end_head); 
	}

	std:: size_t start_bold = input.find ("<b>"); 
	std:: size_t end_bold = input.find ("</b>"); 

	std::cout << start_bold << std::endl;
	std:: cout << end_bold << std::endl;

	if (start_bold != std::string::npos && end_bold != std::string::npos)
	{
		input.insert (start_bold, "*"); 
		input.insert (end_bold, "*"); 
	}
	std::cout << input; 

}
On line 40 you insert a character at the beginning of the string. On line 41, you use the index of a letter calculated before you inserted a character at the beginning of the string.
@cire

Ahhhhh. Thank you for your help!

Best regards,
Jae Kim
Topic archived. No new replies allowed.