string iterator

I am trying to iterate through a file path to extract the file name. since the . separating the name from the extension is a unique character, i thought i would reverse iterate from the . to the first \ separating directories. however, when trying to reference the memory location of the position of the . in the string, i am getting an i-value error:

1
2
3
4
5
6
7
for (std::string::reverse_iterator iter = &(songPath.find('.')); iter != songPath.rend(); ++iter)
{
	if (*iter == '\\')
		break;
	else
		songName.push_back(*iter);
}


string::find returns a size_t position not an iterator or reference. You could subtract the position from rbegin songPath.rbegin() - (songPath.find('.'));
Or use find and rfind
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <string>
#include <iterator>
#include <algorithm>
using namespace std;

int main() {
    string s = "\\this\\is\\a\\path\\file.txt";
    size_t start = s.rfind('\\');
    size_t end = s.find('.', start);
    string t = s.substr(start + 1, end - start - 1);
    cout << t << endl;
}
Last edited on
This ended up being the solution:

1
2
3
4
5
6
7
8
9
10
11
12
auto startiterator = songPath.rend() - songPath.find('.'); // set the starting position of iterator to the location of . in the string

for (std::string::reverse_iterator iter = startiterator; iter != songPath.rend(); ++iter) // step backwards from the . to the first \ and save as name
{
	if (*iter == '\\')
		break;
	else
		songName.push_back(*iter);
}

std::reverse(songName.begin(), songName.end());
transform(songName.begin(), songName.end(), songName.begin(), toupper);
Last edited on
There is already a function that does this sort of things. The link below contains a good example of it.

http://www.cplusplus.com/reference/string/string/find_last_of/
Topic archived. No new replies allowed.