William Payne wrote in news:bp**********@news.island.liu.se:
Hello, consider the following code:
#include <iostream>
#include <string>
void foo(std::string& s);
int main()
{
const char* directory = "c:\\blah";
std::string s = directory;
foo(s);
foo(s);
std::cout << s << std::endl;
return 0;
}
void foo(std::string& s)
{
if(*(s.end()) != '\\')
if ( !s.empty() && *s.rbegin() == '\\' )
{
s += '\\';
}
}
When I run that, the program outputs:
c:\blah\\
I thought (and need it to be) would be:
c:\blah\
What am I doing wrong?
string::end() returns an iterator that is 1 passed the last char
in the string. You should never dereference such an iterator as you
did above (*s.end()) as it isn't actually pointing to anything.
The rbegin() member I use above returns a reverse_iterator (the first
item in the reversed sequence is the last in the forward sequence).
The !s.empty() is required as dereferencing this iterator if s is empty
would be just as bad as derefrenceing s.end().
HTH.
Rob.
--
http://www.victim-prime.dsl.pipex.com/