第五章 5.4.4节练习 & 5.5.1节练习 & 5.5.2节练习 & 5.5.3节练习

练习5.18

说明下列循环的含义并改正其中的错误。

(a)

do

  int v1, v2;

  cout << "Please enter two numbers to sum:";

  if (cin >> v1 >> v2)

     cout << "Sum is: " << v1 + v2 << endl;

while(cin);

(b)

do{

  //...

}while(int ival = get_response());

(c)

do{

  int ival = get_response();

} while(ival);

 解答:

(a)  do while缺少大括号

(b) 如果ival在块中使用到了,那么这段代码就错了

(c) 编译器会提示未定义ival。

int ival;
do{
  ival = get_response();
} while(ival);

练习5.19

编写一段程序,使用do while循环重复执行下述任务:首先提示用户输入两个string对象,然后填出较短那个并输出它。

解答:

#include <iostream>
#include <string>

using namespace std;

int main(){
	do{
		string str1, str2;
		cout << "Please enter two string:\n";
		cin >> str1 >> str2;
		cout << (str1.size() < str2.size() ? str1 : str2) << endl;
	} while (cin);
}

练习5.20

编写一段程序,从标准输入中读取string对象的序列直到连续出现两个相同的单词或者所有单词都读完位置。使用while循环一次读取一个单词,当一个单词连续出现两次时使用break语句终止循环。输出连续重复出现的单词,或者输出一个消息说明没有任何单词是连续重复出现的。

解答:

#include <iostream>
#include <string>

using namespace std;

int main(){
	string word_new, word_old;
	bool flag = true;
	while (cin >> word_new){
		if (word_new == word_old){
			cout << word_old << " is duplicated." << endl;
			flag = false;
			break;
		}
		word_old = word_new;
	}
	if (flag){
		cout << "no words duplicate." << endl;
	}
}

练习5.21

修改5.51节练习题的程序,使其找到的重复单词必须以大写字母开头。

解答:

#include <iostream>
#include <string>
#include <cctype>

using namespace std;

int main(){
	string word_new, word_old;
	bool flag = true;
	while (cin >> word_new){
		if (word_new == word_old && isupper(word_new.at(0))){
			cout << word_old << " is duplicated." << endl;
			flag = false;
			continue;
		}
		word_old = word_new;
	}
	if (flag){
		cout << "no words duplicate." << endl;
	}
}
这个是找到全部满足条件的单词。

练习5.22

本节的最后一个例子跳回到begin,其实是用循环能更好地完成该任务。重写这段代码,注意不再是用goto语句。

解答:

while(1){
  int sz = get_size();
  if(sz <= 0) continue;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值