2010-12-27 7 views
5

문자열이 있습니다. 공백 인 경우 문자열의 마지막 문자를 삭제하려고합니다. 내가 다음 코드,문자열에서 문자 제거

str.erase(remove_if(str.begin(), str.end(), isspace), str.end()); 

을 시도했지만 내 g ++ 컴파일러는 말을 나에게 오류를 제공합니다 :

error: no matching function for call to ‘remove_if(__gnu_cxx::__normal_iterator<char*, 
std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, 
__gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, 
std::allocator<char> > >, <unresolved overloaded function type>)’ 

이 도움을 주시기 바랍니다.

+0

C++하지만 컴파일러는 g ++ ... –

답변

7

첫 번째 문제는 isspace에 C++ 표준 라이브러리의 다중 오버로드가 있다는 것입니다.

#include <string> 
#include <algorithm> 
#include <cctype> 

int main() 
{ 
    std::string str = "lol hi innit"; 
    str.erase(std::remove_if(str.begin(), str.end(), (int(*)(int))isspace), str.end()); 
    std::cout << str; // will output: "lolhiinnit" 
} 

그것은 ++ A가 있지만,이 봐,이 C 못생긴 크다 : 초기 수정 컴파일러의 주소를 가지고하는 기능을하는 알 수 있도록 기능에 대한 명시 적 유형을 제공하는 것입니다.

두 번째로 코드에서 모두 공백을 제거합니다. 이는 원하지 않는 것입니다. 문자열의 마지막 문자에 대한 간단한 if 문을 고려해보십시오.

#include <string> 
#include <cassert> 

int main() 
{ 
    std::string str = "lol hi innit "; 
    assert(!str.empty()); 

    if (*str.rbegin() == ' ') 
     str.resize(str.length()-1); 

    std::cout << "[" << str << "]"; // will output: "[lol hi innit]" 
} 

희망이 있습니다.

-2

당신은 std::remove_if

+0

나는 네임 스페이스 표준을 사용하고 있습니다. –

+0

std :: didnt 도움말을 추가하십시오. –

+0

''도 포함 시켰습니까? – Naveen

6

위해 나는 그것이 isspace이 (오류 메시지에 remove_if에 세 번째 매개 변수로 "해결되지 않은 오버로드 된 함수 타입"에 따라)이 무엇인지 알아낼 수 있다고 생각 누락되었습니다. ::isspace을 시도해보고 ctype.h

+0

yup .. 그게 ... –

+0

나는 std :: isspace ..를 사용하려고 시도했다. : P –

+0

나는'std :: isspace'를 사용하지 않았지만 참조에 따르면 2 개의 인자를 취하고 두 번째 인자는 로케일은 술어로 적합하지 않습니다. – davka

0

나는 당신과 똑같은 문제가있어서 isspace을 없앴습니다. 난 그냥이와 함께 갔다 : 당신을 위해 작동하는 경우를 참조 비주얼 스튜디오 2012을 사용하여 2012 Visual C++에 나를 위해 일한

str.erase(std::remove_if(str.begin(),str.end(),' '),str.end()); 

.