Hi, I was trying the erase method in the std::string.
The string is "David Hardman Junior", and I try to erase everything after the first space. Right after the erase, the string is not readable anymore.
Can anyone help me out here?
std::string str = "David Hardman Junior";
size_t pos = 0;
pos = str.find(" "); //pos is 5 in this case
while( pos != std::string::npos ){
std::string token = str.substr(0, pos); //the string is not readable after this line
str.erase(0, pos);
pos = str.find(" ");
}
The parameters for erase are: erase(starting_position, no._characters_to_be_removed)
In your example above you are starting at the first character, 0, and deleting the next 5 characters so it looks like this:
0 = D
1 = a
2 = v
3 = i
4 = d
These are the five characters removed leaving you with " Ardman Junior"; notice the space that is left before 'A'. This is why in my example 'pos' is equal to how many characters in the space is, but you have to add one to it to actually delete that character.