C++ 将字符串的字符传递给C++;?

C++ 将字符串的字符传递给C++;?,c++,reference,char,parameter-passing,C++,Reference,Char,Parameter Passing,在我的程序中,我希望函数replacef(charm)将字母A/A替换为数字(初始化为char)。但是,当我在for循环中调用该函数时,如果我编写例如“Alabama”(不带引号),程序将返回未更改的字符串。如何传递字符以使此函数正常工作 #include <iostream> #include <string> using namespace std; string n; void replacef(char m) { switch (m) {

在我的程序中,我希望函数replacef(charm)将字母A/A替换为数字(初始化为char)。但是,当我在for循环中调用该函数时,如果我编写例如“Alabama”(不带引号),程序将返回未更改的字符串。如何传递字符以使此函数正常工作

#include <iostream>
#include <string>
using namespace std;
string n;
void replacef(char m)
{
    switch (m)
    {
    case 'A':
    case 'a':
    m='1';
    }
}
int main()
{
    cin>>n;
    for(int i=0; i<n.length(); i++)
    {
        replacef(n[i]);//Replace the current char in the string
    }
    cout<<n<<endl;
}
#包括
#包括
使用名称空间std;
字符串n;
void replacef(字符m)
{
开关(m)
{
案例“A”:
案例“a”:
m='1';
}
}
int main()
{
cin>>n;

对于(int i=0;i您需要通过引用传递参数。替换
void replacef(char&m)
void replacef(char&m)
,您的替换函数必须通过引用接收字符

void replacef( char& c){ ...
我认为您还应该看看std::replace函数,它可以满足您的需要。


M2c

您应该使用引用或指针来执行此操作

以下是执行此操作的代码:-

#include <iostream>
#include <string>
using namespace std;
string n;
void replacef(char &m)
{
    switch (m)
    {
    case 'A':
    case 'a':
    m='n';//you can choose any character to replace in place of 'm'
    }
}
int main()
{
    cin>>n;
    for(int i=0; i<n.length(); i++)
    {
        replacef(n[i]);//Replace the current char in the string
    }
    cout<<n<<endl;
}
#包括
#包括
使用名称空间std;
字符串n;
无效替换(字符和m)
{
开关(m)
{
案例“A”:
案例“a”:
m='n';//您可以选择任何字符替换“m”
}
}
int main()
{
cin>>n;

对于(int i=0;is/
void replacef(char&m)
/
void replacef(char&m)
非常感谢!@Y.Ivanov请参阅。