RE: compiler error question

"Anna-Jayne Metcalfe" <[email protected]>
Newsgroups gmane.comp.windows.off-topic
Message-ID <!&!AAAAAAAAAAAYAAAAAAAAAFpZYOCpua1AsUU25lbUK8bCgAAAEAAAAJ8+EDtEuQJMhkK7up3opTYBAAAAAA==@annasplace.me.uk>
Hi John,

 

>  I need a function that adds an extra backslash to a file path that is
returned by another function. I couldn't find any examples anywhere so I
wrote one of my own and when I compile the code I get the following error:

 

The error means that there are at least two overloaded versions of operator
[] for that type, and the compiler can't work out which one you want. As you
don't say whether you are working in C or C++ (or on which compiler) it's
hard to be more specific than that, but you might want to try changing your
loop variable to type size_t.

 

I would however say that if you are using C++ you really should look at
using a string class (e.g. std::string for cross platform code, or CString
for MFC/ATL code on Windows) for this rather than the C string handling API.

 

For one thing, string libraries make such operations far easier
(ATL::CString can do everything you seek in one line of code, for example).
For another, you are less likely to unwittingly write code containing buffer
overflow issues. Assuming I read what you are trying to do correctly, either
of the following should work:

 

void ReplaceSubstring(std::string& cpstrSource, const std::string&
refcstrSearch, const std::string& refcstrReplace)
{
    std::string::size_type pos = 0;

    while ( (pos = cpstrSource.find(refcstrSearch, pos) ) !=
std::string::npos)
    {
        cpstrSource.replace(pos, refcstrSearch.length(), refcstrReplace);


        pos += refcstrReplace.length();
    }
}

 

std::string path("C:\\This\\is\\a\\test.exe");

 

ReplaceSubstring(path, "\\", "\\\\");

 

 

If you are writing in Visual C++ for Windows, ATL::CString can do this in
one line of code:

 

CString sPath(_T("C:\\This\\is\\a\\test.exe") );



sPath.Replace(_T("\\"), _T("\\\\") );

 

I hope the above helps. Of course, if all you were trying to do is add a
single backslash to the end of the string that's a whole lot easier:

 

path += "\\";

 

 

Cheers,

 

                Anna x

 

                 <http://www.riverblade.co.uk/> http://www.riverblade.co.uk

                MSN IM:  <mailto:[email protected]>
[email protected] (don't ask!)

                Twitterings:  <http://twitter.com/annajayne>
http://twitter.com/annajayne

                Flickr:  <http://www.flickr.com/photos/jalapenokitten/>
http://www.flickr.com/photos/jalapenokitten/
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.