【发布时间】:2014-04-08 20:06:40
【问题描述】:
我做了一个从句子中删除单词的小程序。每次我尝试运行程序时,它都会给我这些错误
错误 2 错误 C2040:“==”:“int”的间接级别不同 来自 'const char [4]' c:\program files (x86)\microsoft visual studio 12.0\vc\include\xutility line:3026 column:1 STL string erase
和
错误 1 错误 C2446:“==”:没有从“const char *”转换为 'int' c:\program files (x86)\microsoft visual studio 12.0\vc\include\xutility line:3026 column:1 STL string erase
这也是我的代码
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main(){
string sample("hello world");
cout << "The sample string is: ";
cout << sample << endl;
//erasing world
cout << "Erasing world" << endl;
sample.erase(5, 10);
cout << sample << endl;
//finding h and erasing it
string::iterator iCharH = std::string::find(sample.begin(), sample.end(), "h");
cout << "finding h and erasing it" << endl;
if (iCharH != sample.end()){
sample.erase(iCharH);
}
cout << sample << endl;
//erasing entirely
sample.erase(sample.begin(), sample.end());
if (sample.length() == 0){
cout << "The string is empty" << endl;
}
system("pause");
return 0;
}
【问题讨论】:
-
请在错误信息中给出行号。
-
std::find只找到单个元素(即字符),而不是子集(即子字符串)。使用std::string::find。 -
转至此参考:std::basic_string::find,了解有关
std::string::find成员函数的四个重载版本的详细信息。将此用于三种不同的擦除重载:std::basic_string::erase. -
用
'h'替换string::iterator iCharH = std::string::find(sample.begin(), sample.end(), "h");中的"h"
标签: c++ string stl runtime-error