2013-04-13 54 views
1

我试图从字符串中删除空格。但抛出一个错误。remove_if尝试删除空白时抛出错误

哪些参数做了我的代码为寻找

我的主要功能

#include <algorithm> 
#include <iostream> 
#include <fstream> 
#include <vector> 
#include <string> 
#include <sstream> 
using namespace std; 


int main() 
{ 
    string myText; 
    myText = readText("file.txt"); 
    myText.erase(remove_if(myText.begin(), myText.end(), isspace), myText.end()); 
    cout << myText << endl; 

    return 0; 
} 

下面是当我尝试编译错误出现做错了..谢谢。

encrypt.cpp: In function ‘int main()’: 
encrypt.cpp:70:70: error: no matching function for call to ‘remove_if(std::basic_string<char>::iterator, std::basic_string<char>::iterator, <unresolved overloaded function type>)’ 
encrypt.cpp:70:70: note: candidate is: 
/usr/include/c++/4.6/bits/stl_algo.h:1131:5: note: template<class _FIter, class _Predicate> _FIter std::remove_if(_FIter, _FIter, _Predicate) 
+0

你能展现包括任何'using'指令/声明? – juanchopanza

+0

@juanchopanza添加了我的包含声明。 – user2017011

+1

啊,'使用命名空间std'再次敲击... – juanchopanza

回答

3

你得到这个错误,因为有两个函数名为isspace

  1. 定义在locale头,空间std

    template<class charT> 
    bool std::isspace(charT ch, const locale& loc); 
    
  2. cctype头文件中定义,全局命名空间

    int isspace(int ch); 
    

所以,如果你想使用第二种功能,你有两种方法:

  1. 不要使用using namespace std。我更喜欢它。
  2. 使用::要调用的函数,在全局命名空间中定义

    remove_if(myText.begin(), myText.end(), ::isspace) 
    //          ^^ 
    
0

有几个详细的解释:

No instance of function template remove_if matches argument list

作为总结,isspace为是ambigous到编译器。我宁愿命令不使用它。下面

代码工作在G ++ 4.7.2

#include<iostream> 
#include<string> 
#include<algorithm> 
using namespace std; 

bool isSpace(const char& c) 
{ 
    return !!::isspace(c); 
} 

int main() 
{ 
    string text("aaa bbb ccc"); 
    text.erase(remove_if(text.begin(), text.end(), isSpace), text.end()); 
    cout << text << endl; 
    return 0; 
} 
相关问题