码迷,mamicode.com
首页 > 编程语言 > 详细

C++Primer第五版 3.2.3节练习

时间:2020-01-12 11:46:22      阅读:72      评论:0      收藏:0      [点我收藏+]

标签:while   namespace   c++   习惯   程序   etl   间接   auto   isp   

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

  

C++Primer第五版 3.2.3节练习

标签:while   namespace   c++   习惯   程序   etl   间接   auto   isp   

原文地址:https://www.cnblogs.com/Kanna/p/12182126.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!