c++ primer(第五版)学习笔记及习题答案代码版(第五章)语句

笔记较为零散,都是自己不熟悉的知识点。

习题答案至于一个.cc 中,需要演示某一题直接修改 #define NUM***, 如运行5.23题为#define NUM523;

chapter 5
1、switch控制流
如果在某处一个带有初值的变量位于作用域之外,在另一处该变量位于作用域之内,不允许扩过变量的初始化语句直接跳转到该变量作用域内的另一个位置。

2、定义在while条件部分或者while循环体内的变量每次迭代都经历从创建到销毁的过程。
  do while语句应该在括号包围起来的条件后面用一个分号表示语句结束。
3、throw & catch异常处理
try{
  if(item1.isbn() != item2.isbn)
      throw runtime_error("Data must refer to same ISBN");
}catch(runtime_error err){
  cout<<err.what()<<"n\Try again"<<endl;

#include <iostream>
#include <vector>
#include <cstring>
#include <stdexcept>
#define NUM525

using namespace std;
int main(){
/*5.1*/
#ifdef NUM51
	cout<< "空语句只含有简单的分号,如: "<<endl;
	; //null statement
	cout<< "当语法上需要一条语句,但是逻辑上不需要时,如: "<<endl;
	int s;
	while(cin >> s && s!= 0)
		; //null statement
#endif
/*5.2*/
#ifdef NUM52
	cout<<"指用花括号括起来的语句和声明的序列。如果在程序的某个地方,预防上需要一条语句,逻辑上需要多条语句,就需要复合语句。"<<endl;
#endif
/*5.3*/
#ifdef NUM53
	int sum = 0, val = 1;
	while(val <= 10)
		sum += val, ++val;
	cout<< "sum of 1 to 10 inclusive is: " << sum <<endl;
	cout<< "可读性变差了。 "<<endl;
#endif
/*5.4*/
#ifdef NUM54
	cout<<"(a) iter初始化没有意义. "<<endl;
	string::iterator iter = s.begin();
	while(iter != s.end()){}
	cout <<"(b) if语句没有在while块中,所以其中的status是无效的,status应该在之前声明。"<<endl;
	bool status;
	while((status = find(word))){  }
	if(!status) {  }
#endif
/*5.5*/
#ifdef NUM55
	int grade;
	const string lettergrade[] = {"F", "D", "C", "B", "A", "A++"};
	cout <<" Enter the grade in number: "<<endl; 
	while(cin >> grade)
		if(grade < 60)
			cout<< "lettergrade is: " << lettergrade[0]<<endl;
		else if(grade == 100)
			cout<< "lettergrade is: " << lettergrade[5]<<endl;
		else
			cout<<"lettergrade is: "<<lettergrade[(grade/10) -5]<<endl;
#endif
/*5.6*/
#ifdef NUM56
	const string scores[] = {"F", "D", "C", "B", "A", "A++"};
	int grade;
	while(cin >> grade){
		string lettergrade = grade < 60  ? scores[0] : scores[(grade-50) / 10];
		cout<<"lettergrade is: " << lettergrade <<endl;
	}
#endif
/*5.7*/
#ifdef NUM57
	cout<<"(a) 第二句少了分号。(b)if语句用{}添加两个语句的块. "
		"(c)第三句改 ' else if(!val) ' ; (d)= 替换为‘==’"<<endl;
#endif
/*5.8*/
#ifdef NUM58
	cout<<"当一个if语句嵌套在另一个if语句内部,if分支多于else分支,多于的else应该匹配那个if。 尽可能的用{ }包含if和else之后的语句。"
#endif
/*5.9*/
#ifdef NUM59
	unsigned aCnt = 0, eCnt =0, iCnt =0, oCnt =0, uCnt =0;
	char ch;
	while(cin >> ch){
		if(ch == 'a')
			++aCnt;
		else if(ch == 'e')
			++eCnt;
		else if(ch == 'i')
			++iCnt;
		else if(ch == 'o')
			++oCnt;
		else if(ch == 'u')
			++uCnt;
	}
    cout << "Number of vowel a: \t" << aCnt << '\n'
         << "Number of vowel e: \t" << eCnt << '\n'
         << "Number of vowel i: \t" << iCnt << '\n'
         << "Number of vowel o: \t" << oCnt << '\n'
         << "Number of vowel u: \t" << uCnt << endl;
#endif
/*5.10*/
#ifdef NUM510
    unsigned aCnt = 0, eCnt = 0, iCnt = 0, oCnt = 0, uCnt = 0;
    char ch;
    while (cin >> ch) {
    	switch (ch) {
    		case 'a':
			case 'A':
    			++aCnt;
    			break;
    		case 'e':
			case 'E':
    			++eCnt;
    			break;
    		case 'i':
			case 'I':
    			++iCnt;
    			break;
    		case 'o':
			case 'O':
    			++oCnt;
    			break;
    		case 'u':
			case 'U':
    			++uCnt;
    			break;
    	}
    }
    // print results
    cout << "Number of vowel a: \t" << aCnt << '\n'
         << "Number of vowel e: \t" << eCnt << '\n'
         << "Number of vowel i: \t" << iCnt << '\n'
         << "Number of vowel o: \t" << oCnt << '\n'
         << "Number of vowel u: \t" << uCnt << endl;
#endif
/*5.11*/
#ifdef NUM511
    unsigned aCnt = 0, eCnt = 0, iCnt = 0, oCnt = 0, uCnt = 0, spaceCnt =0, tabCnt =0, newLineCnt =0;
    char ch;
    while (cin >> ch) {
    	switch (ch) {
    		case 'a':
			case 'A':
    			++aCnt;
    			break;
    		case 'e':
			case 'E':
    			++eCnt;
    			break;
    		case 'i':
			case 'I':
    			++iCnt;
    			break;
    		case 'o':
			case 'O':
    			++oCnt;
    			break;
    		case 'u':
			case 'U':
    			++uCnt;
    			break;
			case ' ':
				++spaceCnt;
				break;
			case '\t':
				++tabCnt;
				break;
			case '\n':
				++newLineCnt;
				break;
    	}
    }
    // print results
    cout << "Number of vowel a: \t" << aCnt << '\n'
         << "Number of vowel e: \t" << eCnt << '\n'
         << "Number of vowel i: \t" << iCnt << '\n'
         << "Number of vowel o: \t" << oCnt << '\n'
         << "Number of vowel u: \t" << uCnt << '\n'
         << "Number of space :  \t" << spaceCnt << '\n'
         << "Number of tab \\t:   \t "<< tabCnt << '\n'
         << "Number of newLine\\n  \t" << newLineCnt << endl;
#endif
/*5.12*/
#ifdef NUM512
    unsigned ffCnt = 0, flCnt = 0, fiCnt = 0;
	char preChar, curChar = '\0';
    char ch;
    while (cin >>noskipws>> curChar) { //noskipws表示cin时不跳过空格和换行
			switch (curChar) {
				case 'f':
					if(preChar == 'f')
					++ffCnt;
					break;
				case 'i':
					if(preChar == 'f')
					++fiCnt;
					break;
				case 'l':
					if(preChar == 'f')
					++flCnt;
					break;
			}
		preChar = curChar;
    }
    cout << "Number of ff: \t" << ffCnt << '\n'
         << "Number of fl: \t" << flCnt << '\n'
         << "Number of fi: \t" << fiCnt << endl;
#endif
/*5.13*/
#ifdef NUM513
	cout<<"(a) case语句后缺少break; (b)分别在case1和default定义了变量,出现了跳过变量的定义和初始化的情况,可以将ix在switch语句前定义。"
		"(c) case标号中不能出现多个值,需分开表示case 1: case 3: case 5: case 7: ;"
		"(d) case标号中只能使用常量表达式,修改第一句定义'const unsigned ival=512, jval = 1024, kval = 4096;'"<<endl;
#endif
/*5.14*/
#ifdef NUM514
	string curWord, preWord, maxWord;
	int count = 0, max  = 0;
	while(cin >> curWord){
		if(curWord == preWord){
			++count;
		}else{
			count = 1;     //must return to 1 in every loop
			preWord = curWord;
		}
		if(max < count){
			max = count;
			maxWord = preWord;
		}
	}
	if(count <= 1)
		cout<< "no word repeated "<<endl;
	else
		cout<< "Max count of word: "<< maxWord<<" occured "  << max <<endl;
#endif
/*5.15*/
#ifdef NUM515
	cout<<"(a)if语句中的ix是未声明的,修改ix在for语句之前定义声明; (b)for语句不完整,修改为'for(;ix !=sz; ++ix)';"
		"(c)++sz会使得for无限循环下去,修改去掉++sz; "<<endl;
#endif
/*5.16*/
#ifdef NUM516
	const size_t size =100;
	int ia[size];
	size_t ix =0;	
	while(ix !=size)
		/* ...*/
		++ix;
	}
	for(size_t ix =0; ix !=size; ++ix){
		/* ...*/
	}
	do{
		/* ...*/
		++ix;	
	}while(ix !=size)
	cout<<"习惯使用for语句,因为其更为简洁,"<<endl;
#endif
/*5.17*/
#ifdef NUM517
	vector<int> vec1 = {0,1,1,2};
	vector<int> vec2 = {0,1,1,2,3,5,8};
	auto size = vec1.size() < vec2.size() ? vec1.size() : vec2.size();
	for(decltype(vec1.size()) li = 0; li != size; ++li){
		if(vec1[li] != vec2[li]){
			cout<< "false" <<endl;
			break;
		}
		if(li == size -1 )
			cout<< "true" <<endl;
	}
#endif
/*5.18*/
#ifdef NUM518
	cout<<"(a)每次读入两个整数,输出它们的和.do while之间缺少{ } " <<endl;	
	do{
		int v1, v2;
		cout << "Please enter two numbers to sum:" ;
      		if (cin >> v1 >> v2)
                cout << "Sum is: " << v1 + v2 << endl;
        }while (cin);
	cout<<"(b)do while循环条件中不能定义变量. "<<endl;
	int ival;
    do {
        // . . .
        } while (ival = get_response()); 
	cout<<"ival是未定的, 应该在do while之前定义. "<<endl;
	int ival = get_response();
	do {
        	ival = get_response();
        } while (ival); 
#endif
/*5.19*/
#ifdef NUM519
	string str1, str2, temp;
	cout<<"Enter two string: "<<endl;
	do{
		cin >> str1 >> str2;
		temp  =  str1.size() > str2.size() ? str2 : str1;
		cout<< "The string size is less: " << temp <<endl;
	}while(cin);
#endif
/*5.20*/
#ifdef NUM520
	string str1, preStr, temp;
	cout<<"Enter string: "<<endl;
	while(cin >> str1){
		if(preStr == str1){
			temp = str1;
			cout<< 	str1 << " Occurs twice. "<<endl;
			break;
		}else if(cin.eof()){
			cout<< "no one occurs twice or more. "<<endl;		
		}		
		preStr = str1;
	}
#endif
/*5.21*/
#ifdef NUM521
	string curStr, preStr;
	bool flag_no = false;
	cout<<"Enter string: " <<endl;
	while(cin >> curStr){
		if(!isupper(curStr[0]))
			continue;
		else if(curStr == preStr){
			cout<< curStr<< " occurs twice. "<<endl;
			flag_no = true;
			break;
		}
		else 
			preStr = curStr;
	}
		if(!flag_no)
			cout<<"no one occurs twice. "<<endl;
#endif
/*5.22*/
#ifdef NUM522
	for(int sz = get_size(); sz <= 0; sz = get_size())
		; //不满足条件执行相同的动作
#endif
/*5.23*/
#ifdef NUM523
	int val1, val2;
	cin >> val1 >> val2;
	cout << val1/val2 <<endl;
#endif
/*5.24*/
#ifdef NUM524
	int val1, val2;
	cin >> val1 >> val2;
	if(val2 == 0)
		throw runtime_error("divisor is 0");
	cout<< static_cast<double>(val1)/(val2) <<endl;
#endif
/*5.25*/
#ifdef NUM525
	int val1, val2;
	cout<<"Enter two numbers: "<<endl;
	while(cin >> val1 >> val2){
		try{
			if(val2 == 0)
			throw runtime_error("divisor is 0");
			cout<< static_cast<double>(val1)/(val2) <<endl;
		}catch(runtime_error err){
			cout<< err.what()<<" \n Try again. "<<endl;
		}
	}
#endif
	return 0;
}
参考资料:
c++ primer中文版第五版,电子工业出版社。
c++ primer第四版习题解答,人民邮电出版社。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值