练习 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;
}