用C++编写:字符串的第一个字符如果是字母要大写,其他字母小写。输入:第一行一个数字 n,表示有 n 个字符串,来 n 行,每行一个单词,长度不超过 20n 不超过 100。 接下
时间: 2023-07-15 17:13:07 浏览: 52
面是一个可能的 C++ 代码实现:
```cpp
#include <iostream>
#include <cstring>
using namespace std;
int main() {
int n;
cin >> n;
getchar(); // 吃掉换行符
while (n--) {
char s[101];
cin.getline(s, 101);
int len = strlen(s);
if (isalpha(s[0])) { // 如果第一个字符是字母
s[0] = toupper(s[0]); // 转为大写
}
for (int i = 1; i < len; i++) {
if (isalpha(s[i])) { // 如果是字母
s[i] = tolower(s[i]); // 转为小写
}
}
cout << s << endl;
}
return 0;
}
```
上述代码用了 C++ 标准库中的 `cstring` 和 `iostream` 头文件。首先读入 `n`,并且用 `getchar()` 吃掉输入缓冲区中的换行符。之后每次读入一行字符串,用 `strlen` 函数得到字符串长度,判断第一个字符是否是字母,如果是则用 `toupper` 函数转为大写。然后遍历字符串中的其它字符,如果是字母则用 `tolower` 函数转为小写。最后输出处理后的字符串,并加上换行符。