C++Primer第五版 3.2.3节练习

练习 3.6:编写一段程序,使用范围for语句将字符串内的所有字符用X代替。
答案见云盘程序

练习 3.7:就上一题完成的程序而言,如果将循环控制变量的类型设为char将发生什么?先估计一下结果,然后实际编程进行验证。
答:合法,可以执行

练习 3.8:分别用while循环和传统的for循环重写第一题的程序,你觉得哪种形式更好呢,为什么?

答:各有千秋,我觉得差不多,看个人习惯,for是条件检验一次,执行到底,while是条件和执行交替执行,检验一下条件,执行一下。

练习 3.9:下面的程序有何作用?它合法吗?如果不合法,为什么?
string s;
cout << s[0] << endl;
答:合法,就是输出一个空串

练习3.10:编写一段程序,读入一个包含标点符号的字符串,将标点符号去除后输出字符串剩余的部分。
答:见云盘程序

练习3.11:下面的范围for语句合法吗?如果合法,C的类型是什么?
const string s = “Keep out!”;
for (auto &c : s) {//}
答:合法,C的类型是const char,不允许通过对c进行赋值修改,从而间接修改S

练习3.6

#include <iostream>
#include <string>

using std::string;
using std::cin;
using std::cout;
using std::endl;

int main()
{
    string s;
    while (cin >> s)
     for(auto &c : s)
        c = 'X';
    cout << s << endl;
    return 0;
 } 

练习3.7

#include <iostream>
#include <string>

using std::string;
using std::cin;
using std::cout;
using std::endl;

int main()
{
    string s;
    while (cin >> s)
     for(char &c : s)
        c = 'X';
    cout << s << endl;
    return 0;
 } 

练习3.8

#include <iostream>
#include <string>

using std::string;
using std::cin;
using std::cout;
using std::endl;

int main()
{
    string s;

    while (cin >> s )
      { /*
        for (decltype(s.size()) index = 0; index != s.size(); ++index)
            s[index] = 'X';
        */
    decltype(s.size()) index = 0;
    while (index != s.size())
        {
            s[index] = 'X';
            ++index;
        }
    }
    cout << s << endl;
    return 0;
}

练习3.10

#include <iostream>
#include <string>

using std::string;
using std::cin;
using std::cout;
using std::endl;

int main()
{
    string s;
    while (cin >> s)
    {   
        string result;
        for (auto &c : s)
          {
            if (!ispunct(c))
                result += c;
          }
        cout << result << endl;
    }
    return 0;
 } 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值