关于字符串小写转大写的问题,如何解决?

编写一个函数,它接受一个指向string对象的引用作为参数,并将该string对象的内容转换为大写,为此可使用表6.4描述的函数toupper()。然后编写一个程序,它通过使用一个循环让您能够用不同的输入来测试这个函数,该程序的运行情况如下:
Enter a string(q to quit):go away GO AWAY
Next string(q to quit):good grief!GOOD GRIEF!
Next string (q to quit):q
Bye.

该回答引用GPTᴼᴾᴱᴺᴬᴵ
以下是一个 C++ 函数,可以接受一个指向 string 对象的引用作为参数,并将该 string 对象的内容转换为大写。


#include <string>
#include <cctype>

void to_upper_case(std::string& str) {
    for (std::string::iterator it = str.begin(); it != str.end(); ++it) {
        *it = std::toupper(*it);
    }
}

在该函数中,我们使用 std::toupper() 函数将每个字符转换为大写字母。然后,我们可以编写一个程序来测试这个函数:

#include <iostream>
#include <string>

void to_upper_case(std::string& str);

int main() {
    std::string str;
    std::cout << "Enter a string (q to quit): ";
    while (getline(std::cin, str)) {
        if (str == "q") {
            break;
        }
        to_upper_case(str);
        std::cout << "Converted string: " << str << std::endl;
        std::cout << "Next string (q to quit): ";
    }
    std::cout << "Bye." << std::endl;
    return 0;
}


在这个程序中,我们使用 getline() 函数读取输入字符串,并将其传递给 to_upper_case() 函数进行大写转换。然后,我们将转换后的字符串输出到标准输出,然后提示用户输入下一个字符串。如果用户输入 "q",则程序退出。

例如,当用户输入以下内容时:

go away GO AWAY
good grief!GOOD GRIEF!
q


程序输出:

Converted string: GO AWAY GO AWAY
Next string (q to quit): Converted string: GOOD GRIEF!GOOD GRIEF!
Next string (q to quit): Bye.


请注意,这个程序可以接受多行输入,因为它使用了 getline() 函数来读取每行输入。

#include <iostream>
#include <string>
#include <cctype>
// cctype 包含字符大小写转换和判断是否为空等方法

using namespace std;

void string_upper(string &str);

int main() {
    string name = "liuzhanhua";
    while (true) {
        cout << "Enter a string(q to quit):";
        cin >> name;
        if (name != "q") {
            string_upper(name);
            cout << name << endl;
        } else {
            cout << "Bye";
            break;
        }
            
    }
    return 0;
}

void string_upper(string &str) {
    for (int i = 0; i < str.size(); i++) {
        str[i] = toupper(str[i]);
    }
}
// size() 方法可以返回string对象的长度