C++Primer第五版 3.2.3节练习

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

#include<iostream>
#include<string>
using namespace std;

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

  

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

合法,可以执行

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

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

练习 3.9:下面的程序有何作用?它合法吗?如果不合法,为什么?

string s;
cout << s[0] << endl;
答:合法,就是输出一个空串

  

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

#include<iostream>
#include<string>
using namespace std;

int main()
{
	string s;
	while (getline(cin, s))
	{
		string result;
		for (char &c : s)
		{
			if (!ispunct(c))//如果c是符号的话会返回1 ,但有! 所以不会传值给result
				result += c;
		}
		cout << result << endl;
	}

	return 0;
}

  

练习3.11:下面的范围for语句合法吗?如果合法,C的类型是什么?

const string s = “Keep out!”;
for (auto &c : s) {/…/}
答:合法,C的类型是const char,不允许通过对c进行赋值修改,从而间接修改S

  

猜你喜欢

转载自www.cnblogs.com/Kanna/p/12182126.html
今日推荐