程序说明:读入一个字符串,当字符串以.结尾且后面无任何数据时,停止读入。读入后的字符串第一个字母必须是大写,
且其余字母均为小写并过滤掉字符之间多余的空格。
运行结果:
Enter a string: the Answer to life, the Universe, and everything
IS 42.
The answer to life, the universe, and everything
is 42.
string.cpp
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
void readString(string& s);
int main() {
string str;
cout << "Enter a string: ";
readString(str);
cout << str << '\n';
return 0;
}
void readString(string& s) {
char c;
do { cin >> c; } while (! isalpha(c)); // 设置字符串必须以字母开头
if (islower(c)) // 如果字符串首字母为小写将其转换为大写
c = toupper(c);
s = c;
/* 当 c = ‘.' 时:
* 将c追加至字符串s末尾处,读入下个字符至c判断其是否为'\n', 如果是结束外层循环;
* 不是则判断其是否为大写字母,并将大写字母转换为小写追加至字符串s末尾处,
* 继续外层循环。
* 当 c != '.' 时:
* 判断其是否为空格,是则将c追加至字符串s末尾处,读入下个字符至c判断其是否为空格
* 直到读入的数据非空格时结束内层循环,判断其是否为大写字母,并将大写字母转换
* 为小写追加至字符串s末尾处,继续外层循环。
*/
while (true) {
if ((c = cin.get()) != '.') {
if (c == ' ') {
s += c;
while ((c = cin.get()) == ' ')
continue;
}
} else {
s += c;
if ((c = cin.get()) == '\n')
break;
}
if (isupper(c))
c = tolower(c);
s += c;
}
}