多个输入的 C++ 大写函数失败

标签 c++ visual-c++

我遇到了一个问题,我将一段大写代码移到了它自己的函数中,因为我想轻松地多次调用它。如果留在主体中,它可以正常工作,但是一旦我将其作为自己的函数调用,它就不会将第二个输入的第一个单词大写。如果我多次调用该函数,所有后续输入都会发生这种情况。我认为我的最后一个变量有问题,但我不确定。

    using namespace std;
    string capitalize(string capitalizeThis)
    {
        getline(cin, capitalizeThis);
        for_each(capitalizeThis.begin(), capitalizeThis.end(), [](char & c) {
        static int last = ' ';
        if (last == ' ' && c != ' ' && isalpha(c))
            c = ::toupper(c); //capitalize if conditions fulfilled 
        last = c; //iterate
    });
    return capitalizeThis;
}
int main()
{
    string eventName, customerName;
    cout << "\nPlease enter your name:" << endl;
    customerName = capitalize(customerName);
    cout << customerName << endl;

    cout << "\nPlease enter the name of your event:" << endl;
    eventName = capitalize(eventName);
    cout << eventName << endl;

    cout << endl << endl;
    system("pause");
    return (0);
}

我的输出看起来像这样:

Please enter your name:
my name
My Name

Please enter the name of your event:
this event
this Event


Press any key to continue . . .

最佳答案

last 的值在函数调用中持续存在,因为它是一个静态变量。这意味着每次调用都使用上一次调用的最后一个字符的值。您可以更改它以每次捕获一个新变量:

string capitalize(string capitalizeThis)
{
    getline(cin, capitalizeThis);
    char last = ' ';
    for_each(capitalizeThis.begin(), capitalizeThis.end(), [&last](char & c) 
    {
        if (last == ' ' && c != ' ' && isalpha(c))
            c = ::toupper(c); //capitalize if conditions fulfilled 
        last = c; //iterate
    });
    return capitalizeThis;
}

请注意,您正在按值传递 string capitalizeThis。您无法在函数中更改传递的字符串的值,因此通过从 main 传递一个字符串您没有做任何事情。
您应该读取 main 中的输入并通过引用将其传递给函数(因为函数无论如何都应该一次做一件事):

void capitalize(string &capitalizeThis)
{       
    char last = ' ';
    for_each(capitalizeThis.begin(), capitalizeThis.end(), [&last](char & c) 
    {
        if (last == ' ' && c != ' ' && isalpha(c))
            c = ::toupper(c); //capitalize if conditions fulfilled 
        last = c; //iterate
    });        
}

然后从 main 调用它

int main()
{
    string eventName, customerName;
    cout << "\nPlease enter your name:" << endl;
    getline(cin, customerName);
    capitalize(customerName);
    cout << customerName << endl;
    ...        
}

关于多个输入的 C++ 大写函数失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45988672/

相关文章:

c++ - 使用 Visual C++ 和 OLEDB 访问数据库

c++ - 如何在c中为函数指定别名

android - OpenCV 安卓 NDK : non-system libraries in linker error

c++ - 线程安全的并行 RNG 比顺序 rand() 慢

c++ - C++ Azure 移动库中的更新功能损坏

c++ - 错误 : expected primary-expression before ‘>’ : templated function that try to uses a template method of the class for which is templated

c++ - 在 n 处计算六次独立运行的斐波那契数的最大和最小时间

visual-c++ - 独立的VC++编译器

c++派生基类Friend函数访问Parent上的private?

c++ - std::disjunction 中的短路模板特化