C++ <读入字符串并过滤掉不合格的字符>

程序说明:读入一个字符串,当字符串以.结尾且后面无任何数据时,停止读入。读入后的字符串第一个字母必须是大写,
且其余字母均为小写并过滤掉字符之间多余的空格。

运行结果:

 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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值