c++从键盘输入一个字符串,将小写字母全部转换成大写字母
时间: 2023-10-01 14:09:56 浏览: 62
可以使用c++中的标准库函数toupper()将小写字母转换成大写字母。下面是一个示例代码:
```c++
#include <iostream>
#include <string>
#include <locale>
int main() {
std::string str;
std::getline(std::cin, str); // 从键盘输入字符串
std::locale loc;
for (std::string::size_type i = 0; i < str.length(); i++) {
str[i] = std::toupper(str[i], loc); // 将小写字母转换成大写字母
}
std::cout << str << std::endl; // 输出转换后的字符串
return 0;
}
```
在上面的代码中,我们首先使用std::getline()函数从键盘输入一个字符串,然后使用std::locale()构造一个本地化对象,用于处理不同语言环境下的字符转换。接着使用for循环遍历字符串中的每个字符,调用std::toupper()函数将小写字母转换成大写字母,最后输出转换后的字符串。
相关问题
从键盘输入一个字符串 将小写字母全部转换成大写字母 然后输入到一个新键盘文件能保存的
答案:可以使用toupper()函数将小写字母转换成大写字母,然后将结果保存到一个新的文件中。具体实现可以参考以下代码:
```c++
#include <iostream>
#include <fstream>
#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]);
}
}
// 将结果保存到文件中
ofstream outfile("new_keyboard.txt");
if (outfile.is_open()) {
outfile << str;
outfile.close();
cout << "转换成功,结果已保存到 new_keyboard.txt 文件中。" << endl;
} else {
cout << "无法打开文件 new_keyboard.txt。" << endl;
}
return 0;
}
```
C++将字符串中的小写字母转换成大写字母
可以使用C++的标准库函数toupper()将字符串中的小写字母转换成大写字母,具体的实现如下:
```c++
#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;
int main()
{
string str = "Hello, World!";
int len = str.length();
for(int i=0; i<len; i++)
{
if(islower(str[i])) // 判断是否为小写字母
{
str[i] = toupper(str[i]); // 转换成大写字母
}
}
cout << str << endl;
return 0;
}
```
在上述代码中,我们首先定义了一个字符串变量str,并且获取了其长度len。然后利用for循环遍历字符串中的每一个字符,判断其是否为小写字母,如果是,则调用toupper()函数将其转换成大写字母。最后输出转换后的字符串即可。