Re: compiler error question
Stoyan Damov <[email protected]>
| Newsgroups | gmane.comp.windows.off-topic |
|---|---|
| Message-ID | <[email protected]> |
... or use boost::stringalgo::replace[Xxx] ;) On Mon, May 31, 2010 at 9:32 PM, Anna-Jayne Metcalfe <[email protected] > wrote: > > > 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 > > MSN IM: [email protected] (don't ask!) > > Twitterings: http://twitter.com/annajayne > > Flickr: http://www.flickr.com/photos/jalapenokitten/ > > > >