Elu*_*ium 2 c++ arrays string char
对于任何可能的重复问题,提前抱歉.我一直在谷歌搜索我的编译器错误的解决方案,一个星期了,尝试了不同的解决方法,从这里的各种答案,但我不断得到一些错误.
我目前正在学习C++,试图建立一个程序来完成基本的东西,如元音/辅音计数,删除字母等.一切正常,直到我找到自定义字母删除部分.基本上,使用字符函数(根据我的知识)几乎不可能这样做,而转换为字符串似乎会产生其他类型的错误.
这是我不断收到错误的代码片段:
if (strcmp (service, key4) ==0)
{
string str(s);
cout<<endl<<"Please insert the letter you would like removed from your "<<phrasal<<":"<<endl;
cin>>letterToRemove;
s.erase(remove(s.begin(), s.end(),letterToRemove), s.end());
cout<<endl<<s<< "\n"<<endl;
}
Run Code Online (Sandbox Code Playgroud)
这里是我使用的初始化变量:
int main()
{
char s[1000], phrasal[10], service[50], key1[] = "1", key2[] = "2", key3[] = "3", key4[] = "4", key5[] = "5", key6[] = "6", key0[] = "0", *p, letterToRemove;
int vowel=0, vowel2=0, consonant=0, consonant2=0, b, i, j, k, phrase=0, minusOne, letter, idxToDel;
void pop_back();
char *s_bin;
Run Code Online (Sandbox Code Playgroud)
如您所见,原始's'是一个char数组.在第一个代码示例中,我尝试将其转换为字符串数组(字符串str(s)),但这会导致以下编译错误:
我尝试过的另一种解决方法是:
if(strcmp(service, key4)==0)
{std::string s(s);
cout<<endl<<"Please insert the letter you would like removed from your "<<phrasal<<":"<<endl;
cin>>letterToRemove;
s.erase(remove(s.begin(), s.end(),letterToRemove), s.end());
cout<<endl<<s<< "\n"<<endl;
}
Run Code Online (Sandbox Code Playgroud)
现在这是有趣的部分,我没有得到任何错误,但是一旦我选择了自定义字母删除功能,调试就会崩溃.这就是它所说的:
任何帮助将非常感激,坚持这一个一个星期吧!
PS如果我或主持人在回答完问题后删除了这个问题,这样可以吗?我很确定我不是第一个问这个问题的人,但是,正如之前提到的那样,即使在回答了类似问题的答案后,我仍然会遇到这些错误.
对于char数组,您必须使用
std::remove而不是erase,并手动插入null-terminator:
auto newEnd = std::remove(std::begin(s), std::end(s), letterToRemove);
*newEnd = '\0';
Run Code Online (Sandbox Code Playgroud)