这是我的代码,但它说replace is not declared in this scope
这不是正确的语法吗?
#include<iostream>
#include<string>
using namespace std;
int main ()
{
string string_to_edit;
cout<<"Enter a string to replace all the vowels:"<<endl;
cin>>string_to_edit;
string output_string=replace(string_to_edit.begin(),string_to_edit.end(),"a","x");
cout<<output_string<<endl;
return 0;
}
答案 0 :(得分:5)
std::replace
需要#include <algorithm>
,但您还需要使用单个字符。请注意单引号:
replace(string_to_edit.begin(),string_to_edit.end(),'a','x');
另请注意,replace
将替换现有元素。 std::replace
会返回void
。
答案 1 :(得分:3)
std::replace
为declared in <algorithm>
,因此您必须#include <algorithm>
您还需要进行其他两项更改:
replace
返回void
,因此如果您希望replace
d字符串与原始字符串分开,则需要复制原始字符串并将其传递给{{ 1}}。replace
需要单replace
个,而不是字符串;但是你传递了一个以char
和"a"
开头的以字母结尾的字符串。包含这两项变更的代码:
"x"