写一c++代码将用户输入的字母大小写转换
时间: 2024-03-14 20:45:38 浏览: 21
以下是将用户输入的字母大小写转换的 C++ 代码:
```c++
#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;
int main()
{
string str;
cout << "请输入字符串:";
getline(cin, str);
// 将字符串中的小写字母转换为大写字母
for (int i = 0; i < str.length(); i++) {
if (islower(str[i])) {
str[i] = toupper(str[i]);
}
}
cout << "转换为大写字母后的字符串为:" << str << endl;
// 将字符串中的大写字母转换为小写字母
for (int i = 0; i < str.length(); i++) {
if (isupper(str[i])) {
str[i] = tolower(str[i]);
}
}
cout << "转换为小写字母后的字符串为:" << str << endl;
return 0;
}
```
运行程序后,用户输入字符串后,程序会分别将其中的小写字母和大写字母转换为对应的大小写,并输出结果。
希望这个程序能够帮到你!
相关问题
c++大小写字母转换代码
以下是一个简单的C++大小写字母转换代码示例:
```c++
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string str = "Hello World";
transform(str.begin(), str.end(), str.begin(), ::tolower); // 将字符串中的大写字母转换为小写字母
cout << str << endl; // 输出 hello world
transform(str.begin(), str.end(), str.begin(), ::toupper); // 将字符串中的小写字母转换为大写字母
cout << str << endl; // 输出 HELLO WORLD
return 0;
}
```
这个示例使用了 `transform` 函数,它可以将一个序列中的每个元素应用一个函数,并将结果存储到另一个序列中。在这个示例中,我们将 `str` 字符串中的每个字符应用 `::tolower` 或 `::toupper` 函数,从而实现大小写字母的转换。
c++字母大小写转换
在C++中,可以使用toupper()和tolower()函数来进行字母大小写转换。这两个函数都需要一个字符作为参数,并返回转换后的字符。toupper()函数将小写字母转换为大写字母,而tolower()函数则将大写字母转换为小写字母。需要注意的是,这些函数只会对字母字符进行大小写转换,对于非字母字符,它们不会产生任何影响。
下面是一个简单的示例代码,演示了如何使用toupper()和tolower()函数进行字母大小写转换:
```
#include <iostream>
#include <cctype>
using namespace std;
int main()
{
char ch = 'a';
cout << "Original character: " << ch << endl;
// Convert to uppercase
ch = toupper(ch);
cout << "Uppercase character: " << ch << endl;
// Convert to lowercase
ch = tolower(ch);
cout << "Lowercase character: " << ch << endl;
return 0;
}
```