《C++ Primer Plus(第六版)》(8)(第六章 分支语句和逻辑运算符 笔记和答案)
=============笔记=============
1.字符函数库头文件<cctype>
isalnum() 字母或数字
isalpha() 字母
iscntr() 控制字符
isdigit() 数字(0-9)
isgraph() 空格之外的打印字符
islower() 小写字母
isprint() 打印字符,包括空格
ispunct() 标点符号
isspace() 标准空白字符,如空格、进纸、回车、水平制表符、垂直制表符
isupper() 大写字母
isxdigit() 十六进制字符
tolower() 如果是大写,转小写
toupper() 如果是小写,转大写
2.如果既可以使用if else if 又可以使用switch,当选项超过3个的时候,应该使用switch,效率会更高。
3.文件输出。如果不填绝对路径,生成的文件是在程序的目录下的。因为现在在用MacBook,找了半天才找到。真是日了狗了了。
char automobile[50]; int year; double a_price; double d_price; ofstream of;//声明一个输出的对象 of.open("/Users/feiyin001/Documents/myTest.txt");//打开文件 cout << "Enter the make and model of automobile: "; cin.getline(automobile, 50); cout << "Enter the model year: "; cin >> year; cout << "Enter the original asking price: "; cin >> a_price; d_price = 0.913 * a_price; //控制台输出 cout << fixed; cout.precision(2); cout.setf(ios_base::showpoint); cout << "Make and model: " << automobile <<endl; cout << "Year: " << year <<endl; cout << "Was asking $ " << a_price << endl; cout << "Now asking $ " << d_price << endl; //文件输出 of << fixed; of.precision(2); of.setf(ios_base::showpoint); of << "Make and model: " << automobile <<endl; of << "Year: " << year <<endl; of << "Was asking $ " << a_price << endl; of << "Now asking $ " << d_price << endl; of.close();结果:
myTest.txt
Make and model: fdsa
Year: 0
Was asking $ 0.00
Now asking $ 0.00
4.读取文件。基本没怎么做过读写文本的事情。还是得亲自打一下代码。
myTest.txt
12331 3123
2312
3 123 12
321
3
123
3123
ifstream ifile; string filename = "/Users/feiyin001/Documents/myTest2.txt"; ifile.open(filename); if(!ifile.is_open()) { cout << "Could not open the file " << filename << endl; cout << "Program terminating." <<endl; exit(EXIT_FAILURE); } double value = 0; double sum = 0; int count = 0; ifile >> value; while (ifile.good()) { ++count; sum += value; ifile >> value; } //读取停止,检测一下原因 if (ifile.eof()) cout << "End of file reached.\n"; else if (ifile.fail()) cout << "Input terminated by data mismatch.\n"; else cout << "Input terminated for unknown reason.\n"; if (count == 0) { cout << "No data processed.\n"; } else { cout << "Item read: " << count << endl; cout << "Sum: " << sum << endl; cout << "Average: " << sum / count << endl; } ifile.close();结果:
控制台
End of file reached.
Item read: 9
Sum: 18351
Average: 2039
============答案================
6.10 复习题1.第二个判断少一点,如果第一个if成立,esle后面的if就不用判断了。
2.
6.2代码
char ch; std::cout<< "type, and I shall repeat. \n"; cin.get(ch); while (ch != '.') { if (ch == '\n') { cout << ch; } else { cout <<++ch; } std::cin.get(ch); } cout<< "\nPlease excuse the slight confusion.\n";结果:
type, and I shall repeat.
welcome to fable game.
xfmdpnf!up!gbcmf!hbnf
Please excuse the slight confusion.
++ch对每个输入的字符都+了1,变成下一个字符。
如果改成ch + 1,因为要类型转换,就变成整形了,输出的是数字。
修改:
char ch; std::cout<< "type, and I shall repeat. \n"; cin.get(ch); while (ch != '.') { if (ch == '\n') { cout << ch; } else { cout <<ch + 1; } std::cin.get(ch); } cout<< "\nPlease excuse the slight confusion.\n";结果:
type, and I shall repeat.
welcom to fable game。
120102109100112110331171123310398991091023310498110102
Please excuse the slight confusion.
3.
char ch; int ct1 = 0, ct2 = 0; while ((ch = cin.get()) != '$') { cout << ch; ct1++; if (ch = '$') { ct2++; } cout << ch; } cout << "ct1 = " << ct1 << " , ct2 = " << ct2 << "\n";结果:没看清是=号,猜错答案了。。。不过输入之后,编译器会提示的。
Hi!
H$i$!$
$Send $10 or $20 now!
S$e$n$d$ $ct1 = 9 , ct2 = 9
a. weight >= 115 && weight < 125 b. 'q' == ch || 'Q' == ch c. x % 2 == 0 && x != 26 d. x % 2 == 0 && x % 26 != 0 e. (donation >= 1000 && donation <= 2000) || 1 == guest f. (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')
6. x < 0? -x:x
7.
switch (ch) { case 'A': a_grade++; break; case 'B': b_grade++; break; case 'C': c_grade++; break; case 'D': d_grade++; break; default: f_grade++; break; }
9.
int line = 0; char ch; while ( cin.get() && ch != 'Q') { if (ch == '\n') { line++; } }
6.11 编程练习
1.用惯了stl,不用vector真不知道怎么回文显示。
char ch; vector<char> cs; while (cin.get(ch) && ch != '@') { if (isdigit(ch)) { continue; } if (isupper(ch)) { cs.push_back(tolower(ch)); } else if (islower(ch)) { cs.push_back(toupper(ch)); } else { cs.push_back(ch); } } for (int i = (int)cs.size() - 1; i >= 0; i--) { cout<< cs[i]; } cout<<endl;结果:
Welcom to Fable Game!
@
!EMAg ELBAf OT MOCLEw
2.
double ch; vector<double> cs; cin>>ch; double total; while (cin.good()) { cs.push_back(ch); total += ch; cin >> ch; } if (cs.empty()) { cout << "no data"; return; } double average = total / cs.size(); int count = 0; for (int i = 0; i < (int)cs.size(); ++i) { if (cs[i] > average) { ++count; } } cout<< "average: "<< average << " larger count: "<< count << endl;
3.
cout<< "Please enter one of the following choices:" <<endl; cout<< "c) carnivore p) pianist"<<endl; cout<< "t) tree g) game"<<endl; char ch; cin>>ch; char cs[20]; bool flag = true; while (flag) { switch (ch) { case 'c': strcpy(cs , "carnivore"); flag = false; break; case 'p': strcpy(cs , "pianist"); flag = false; break; case 't': strcpy(cs , "tree"); flag = false; break; case 'g': strcpy(cs , "game"); flag = false; break; default: flag = true; cout<<"Please enter a c, p, t, or g: "; cin >> ch; break; } } cout<< "A maple is a "<< cs << endl;
4.老是用char和[]真是不习惯。。。
const int strsize = 50; struct bop { char fullname[strsize]; // real name char title[strsize]; // job title char bopname[strsize]; // secret BOP name int preference; // 0 = fullname, 1 = title, 2 = bopname }; void init(bop bops[], int num) { char buffer[strsize]; for (int i = 0; i < num; ++i) { sprintf(buffer,"fullname%d",i); strcpy(bops[i].fullname, buffer); sprintf(buffer,"title%d",i); strcpy(bops[i].title, buffer); sprintf(buffer,"bopname%d",i); strcpy(bops[i].bopname, buffer); bops[i].preference = i%3; } } void printInfo(bop bops[], int num, char ch) { for (int i = 0; i < num; ++i) { switch (ch) { case 'a': cout<< bops[i].fullname<<endl; break; case 'b': cout << bops[i].title <<endl; break; case 'c': cout << bops[i].bopname <<endl; break; case 'd': if ( bops[i].preference == 0) { cout<< bops[i].fullname<<endl; } else if (bops[i].preference == 1) { cout << bops[i].title <<endl; } else if (bops[i].preference == 2) { cout << bops[i].bopname <<endl; } break; } } } void CTestManager::testCpp() { bop bops[5]; init(bops, 5); cout << "Benevolent Order of Programmers Report"<< endl; cout << "a. display by name b. display by title"<<endl; cout << "c. display by bopname d. display by preference"<<endl; cout << "q. quit"<<endl; cout << "Enter your choice: "; char ch; bool flag = true; cin >> ch; while (flag) { switch (ch) { case 'a': case 'b': case 'c': case 'd': printInfo(bops, 5, ch); cout << "Next choice: "; cin >> ch; break; case 'q': cout << "Bye!" << endl; flag = false; break; default: cout << "Enter your choice: a, b, c, d, or q:"; cin >> ch; break; } } }
5.
int money = 0; cout << "Please enter tvarps: "; cin >> money; while (cin.good() && money > 0) { int tax = 0; if (money > 35000) { tax += (money - 35000) * 0.2; money = 35000; } if (money > 15000) { tax += (money - 15000) * 0.15 money = 15000; } if (money > 5000) { tax += (money - 5000) * 0.1; money = 5000; } if (money <= 5000) { tax += money * 0.0; money = 0; } cout << "tax: "<< tax <<endl; cout << "Please enter tvarps: "; cin >> money; }
6.
struct SPlayer { string name; double money; }; int num = 0; cout << "Please enter player num:"; cin >> num; SPlayer* players = new SPlayer[num]; int grandCount = 0; for (int i = 0; i < num; ++i) { cout << "name: "; cin>> players[i].name; cout << "money: "; cin >>players[i].money; if (players[i].money >= 10000) { ++grandCount; } } cout<<"====Grand Patrons===="<<endl; if (grandCount > 0) { for (int i = 0; i < num; ++i) { if (players[i].money >= 10000) { cout << players[i].name<<endl; } } } else{ cout<<"none"<<endl; } cout<<"====Patrons===="<<endl; if (num - grandCount > 0) { for (int i = 0; i < num; ++i) { if (players[i].money < 10000) { cout << players[i].name<<endl; } } } else{ cout<<"none"<<endl; } delete[] players;
结果:
Please enter player num:5
name: 01
money: 1231
name: 2
money: 234
name: 3
money: 233333
name: 4
money: 3333
name: 5
money: 99999
====Grand Patrons====
3
5
====Patrons====
01
2
4
char ch[50]; int otherCount = 0; int vowel = 0; int consonant = 0; cout <<"Enter words (q to quit):"<<endl; cin >> ch; while (strcmp(ch, "q") != 0) { if (isalpha( ch[0])) { if (ch[0] == 'a' || ch[0] == 'A' || ch[0] == 'e' || ch[0] == 'E' || ch[0] == 'i' || ch[0] == 'I' || ch[0] == 'o' || ch[0] == 'O' || ch[0] == 'u' || ch[0] == 'U' ) { ++vowel; } else { ++consonant; } } else{ ++otherCount; } cin >> ch; } cout << vowel << " words beginning with vowels\n"; cout << consonant << " words beginning with consonants\n"; cout << otherCount << " others\n";
结果:
Enter words (q to quit):
The 12 awesome oxen ambled
quietly across 15 meters of lawn. q
5 words beginning with vowels
4 words beginning with consonants
2 others
8.
ifstream ifile; string filename = "/Users/FableGame/Documents/myTest2.txt"; ifile.open(filename); if(!ifile.is_open()) { cout << "Could not open the file " << filename << endl; cout << "Program terminating." <<endl; exit(EXIT_FAILURE); } char ch = 0; int count = 0; ifile >> ch; while (ifile.good()) { ++count; ifile >> ch; } //读取停止,检测一下原因 if (ifile.eof()) cout << "End of file reached.\n"; else if (ifile.fail()) cout << "Input terminated by data mismatch.\n"; else cout << "Input terminated for unknown reason.\n"; if (count == 0) { cout << "No data processed.\n"; } else { cout << "Char read: " << count << endl; } ifile.close();
9.其实读文件和cin是一样的,忘记字符串和数字交替会有问题,调了一会儿。
struct SPlayer { char name[50]; double money; }; int num = 0; ifstream ifile; string filename = "/Users/feiyin001/Documents/myTest2.txt"; ifile.open(filename); if(!ifile.is_open()) { cout << "Could not open the file " << filename << endl; cout << "Program terminating." <<endl; exit(EXIT_FAILURE); } ifile >> num; ifile.get(); SPlayer* players = new SPlayer[num]; int grandCount = 0; for (int i = 0; i < num; ++i) { ifile.getline(players[i].name, 50,'\n'); cout << "name: " << players[i].name << endl; ifile >>players[i].money; ifile.get(); cout << "money: " << players[i].money<< endl; if (players[i].money >= 10000) { ++grandCount; } } ifile.close(); cout<<"====Grand Patrons===="<<endl; if (grandCount > 0) { for (int i = 0; i < num; ++i) { if (players[i].money >= 10000) { cout << players[i].name<<endl; } } } else{ cout<<"none"<<endl; } cout<<"====Patrons===="<<endl; if (num - grandCount > 0) { for (int i = 0; i < num; ++i) { if (players[i].money < 10000) { cout << players[i].name<<endl; } } } else{ cout<<"none"<<endl; } delete[] players;
结果:
name: Sam Stone
money: 2000
name: Freida Flass
money: 100500
name: Tammy Tubbs
money: 5000
name: Rich Raptor
money: 55000
====Grand Patrons====
Freida Flass
Rich Raptor
====Patrons====
Sam Stone
Tammy Tubbs