a)while(string::iterator iter != s.end()){/*... */}// 未初始化 iter 的值// 修改如下
string::iterator iter = s.begin();while(iter != s.end()){/*... */}
b)while(bool status =find(word)){/*... */}if(!status){/*... */}// status 不能在 while 循环外获取// 修改如下while(bool status =find(word)){if(!status){/*... */}/*... */}
a)for(int ix =0; ix != sz;++ix){/*... */}if(ix != sz)// ix 不能在 for 循环外使用// ...// 修改如下int ix =0;for(; ix != sz;++ix){/* ... */}if(ix != sz)// ...
b)int ix;for(ix != sz;++ix){/*... */}// for 循环少了一条语句且 ix 未被初始化// 修改如下for(int ix =0; ix != sz;++ix){/*... */}
c)for(int ix =0; ix != sz;++ix,++sz){/*...*/}// for 循环永远不会停止// 修改如下for(int ix =0; ix != sz;++ix){/*...*/}
Ex5.17
#include<iostream>#include<vector>usingnamespace std;intmain(){
vector<int> v1,v2;int a=0,b=0;while(cin>>a)
v1.push_back(a);
cin.clear();// 清除ctrl z 状态 让 cin >> b 能进行下去 while(cin>>b)
v2.push_back(b);if(v1.size()<v2.size()){int i=0;while(i != v1.size()&& v1[i]== v2[i]){++i;}if(i==v1.size()){
cout<<" v1 is prefix of v2 "<<endl;
cout<<" true "<<endl;}else
cout<<" false "<<endl;}else{int i=0;while(i != v2.size()&& v1[i]== v2[i]){++i;}if(i==v2.size()){
cout<<"v2 is prefix of v1"<<endl;
cout<<" false "<<endl;}else
cout<<" flase "<<endl;}system("pause");return0;}
Exercises Section 5.4.4
Ex5.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)// while 括号后面的变量必须是事先声明了的; 修改如下int ival =get_response();do{// ...}while(ival);
c)// ival 不能在 while 循环外使用;修改如下int ival =get_response();do{}while(ival);
Ex5.19
#include<iostream>#include<string>usingnamespace std;intmain(){do{
string s1, s2;
cout <<"Please enter two string :"<< endl;if(cin >> s1 >> s2){if(s1 > s2)
cout <<"s2 is less than s1"<< endl;elseif(s1 < s2)
cout <<"s1 is less than s2"<< endl;else
cout <<"two string are equal"<< endl;}}while(cin);system("pause");return0;}
int sz =get_size();while(sz <=0){
sz =get_size();}
Exercises Section 5.6.3
Ex5.23
#include<iostream>usingnamespace std;intmain(){int v1, v2;
cout <<"Please enter two numbers: ";
cin >> v1 >> v2;while(v2 ==0){
cout <<"The second number is zero, please enter another value: ";
cin >> v2;}
cout <<"The result is "<< v1 / v2 << endl;system("pause");return0;}
Ex5.24
#include<iostream>usingnamespace std;intmain(){int v1, v2;
cout <<"Please enter two numbers: ";
cin >> v1 >> v2;if(v2 !=0){
cout <<"The result is "<< v1 / v2 << endl;system("pause");return0;}else{
cerr <<"The second number is zero!"<< endl;system("pause");return-1;}}
Ex5.25
#include<iostream>usingnamespace std;intmain(){int v1, v2;
cout <<"Please enter two numbers: ";
cin >> v1 >> v2;try{if(v2 ==0)throwruntime_error("The second number is zero!");}catch(runtime_error err){
cout << err.what()<<" Please enter another value: ";
cin >> v2;}
cout <<"The result is "<< v1 / v2 << endl;system("pause");return0;}