【问题标题】:Passing char of a string to a function in C++?将字符串的char传递给C++中的函数?
【发布时间】:2017-12-28 08:56:30
【问题描述】:

在我的程序中,我希望函数 replacef(char m) 将字母 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;
}

【问题讨论】:

  • s/void replacef(char m)/void replacef(char&amp; m)

标签: c++ reference char parameter-passing


【解决方案1】:

您需要通过引用传递参数。将void replacef(char m) 替换为void replacef(char&amp; m)

【讨论】:

【解决方案2】:

您的替换函数必须通过引用接收字符。

void replacef( char& c){ ...

我认为您还应该看看 std::replace 函数,它可以满足您的需要。 http://en.cppreference.com/w/cpp/algorithm/replace

M2c

【讨论】:

    【解决方案3】:

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

    这是执行此操作的代码:-

    #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;
    }
    

    如果您还有任何疑问,请发表评论

    【讨论】:

      猜你喜欢
      • 2019-09-28
      • 2011-01-21
      • 2013-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-09
      • 1970-01-01
      相关资源
      最近更新 更多