2
votes

I am trying to convert a file path which just have one slash to double slash as shown on the code below. but it gives me the error shown at the end

    #include<algorithm>

    std::string file_path;
    using std::replace;
     while(fgets(fname_buffer,1024,flist))
   {
    token = strtok( fname_buffer," ,\t");
    file_size=atol(token);

    token = strtok(NULL, " ,\t"); 
   strncpy((char*)file_fp,token,32);
   file_fp[32]='\0';

    token = strtok(NULL, "\n");
    file_path=token;
    replace(file_path.begin(),file_path.end(),'\\',"\\\\");
    //file_path.replace(file_path.begin(),file_path.end(),'\\','\\\\');

error C2664: 'std::basic_string<_Elem,_Traits,_Ax> &std::basic_string<_Elem,_Traits,_Ax>::replace(unsigned int,unsigned int,const _Elem *,unsigned int)' : cannot convert parameter 1 from 'std::_String_iterator<_Elem,_Traits,_Alloc>' to 'unsigned int'

3
Use this. It's much better than the search-replace-repeat algorithms.Benjamin Lindley

3 Answers

2
votes

replace cannot replace one character '\\' with two characters "\\\\". The signature of the template method requires const T& for the last two parameters, but you are passing a string instead of a character.

Here is how you can do what you need:

int p = 0;
while ((p = file_path.find('\\', p)) != string::npos) {
    file_path.insert(p, "\\");
    p += 2;
}
1
votes

You are trying to replace a char-type with a string - replace requires the types to be the same:
const T& which in both cases this should be char.

template < class ForwardIterator, class T >
  void replace ( ForwardIterator first, ForwardIterator last,
                 const T& old_value, const T& new_value );

Here is a code snippet you may find helpful:
(It works by repeated calls to std::string::replace() until end-of-string)

std::string& sReplaceAll(std::string& sS, 
                         const std::string& sWhat, 
                         const std::string& sReplacement)
{
    size_t pos = 0, fpos;
    while ((fpos = sS.find(sWhat, pos)) != std::string::npos)
    {
        sS.replace(fpos, sWhat.size(), sReplacement);
        pos = fpos + sReplacement.size();
    }
    return sS;
}

In your case you would use it like this:

sReplaceAll(file_path, "\\", "\\\\");

0
votes

copy, replace, transform and some other algorithms can't create more elements than exist in their input range. (off the top of my head I can't think of any standard algorithms that do allow this)

You can use regex_replace to do this:

file_path = std::regex_replace(file_path,std::regex("\\"),"\\\\");