2012-03-01 2 views
2

아래 코드 에서처럼 슬래시가 하나만있는 파일 경로를 이중 슬래시로 변환하려고합니다. 그러나 그것은 나에게std :: replace 오류가 발생했습니다

#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(),'\\','\\\\'); 

오류 C2664 마지막에 표시되는 오류가 있습니다 : '표준 : < _Elem, _Traits을 basic_string, _Ax이 &에게 표준 : < _Elem, _Traits, _Ax을 basic_string> :: 교체>를 (부호없는 INT, 부호없는 INT는 const를 _Elem * 서명되지 않은 INT는) : 당신은 대체하려는

+0

사용 [이] (HTTP : // WWW를. boost.org/doc/libs/1_49_0/doc/html/boost/algorithm/replace_all.html). search-replace-repeat 알고리즘보다 훨씬 낫습니다. –

답변

2

replace는 하나 개의 문자를 대체 할 수 '\\' 두 개의 문자 "\\\\". 템플릿 메서드의 서명에는 마지막 두 매개 변수에 const T&이 필요하지만 문자 대신 문자열을 전달합니다.

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

그것은'file_path 여야합니다.insert (p, "\\\\"); ' –

+0

@AgnelKurian 아니, 정말로 : 다른 슬래시가 이미 있습니다. – dasblinkenlight

+0

맞아 !! 나는 그것을 지금 이해한다. –

1

'부호 INT'에 ':: _ String_iterator < _Elem, _Traits, _Alloc> 표준'에서 매개 변수 1 변환 할 수 없습니다 ' 문자열 대체가있는 char 유형은 유형이 동일해야합니다.
const T & 두 경우 모두 이어야합니다.
사건이처럼을 사용에서

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; 
} 

을 (그것은 끝 문자열까지 std::string::replace()에 반복 호출에 의해 작동) : 여기

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

는 코드가 당신이 도움이 될 수있는 니펫을 수 있습니다 :

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

+1

해결책을 제시하는 것이 좋습니다. 여기서 '\\'를''\\ "'로 바꾸면 코드가 작동합니다. –

+0

@MatthieuM : 그런 식으로 작동하지 않았습니다 (런타임 오류가 발생했습니다). 다른 방법은 둥근지만 경로의 모든 문자를 '\'로 대체했습니다. – John

+2

'char * '는'char'에 할당 될 수 없기 때문에 동작 할 것이라고 생각하지 않습니다. 이것은'std :: 문자열'. – hmjd

0

copy, replace, transform 일부 다른 알고리즘은 입력 범위에 존재하는보다 많은 요소를 만들 수 없습니다 : 여기

는 당신이 필요로 할 수있는 방법이다. 당신은이 작업을 수행 할 regex_replace을 사용할 수 있습니다

(내 머리 위로 떨어져 나는 이것을 허용 할 표준 알고리즘을 생각할 수 없다) :

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

컴파일러가 regex_replace가 std – John

+0

'#include '의 멤버가 아니라고합니다. VS2010 이전 버전의 VS를 사용한다면'std :: tr1' 버전을 사용해야합니다. – bames53

관련 문제