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