CXYVIP官网源码交易平台_网站源码_商城源码_小程序源码平台-丞旭猿论坛
CXYVIP官网源码交易平台_网站源码_商城源码_小程序源码平台-丞旭猿论坛
CXYVIP官网源码交易平台_网站源码_商城源码_小程序源码平台-丞旭猿论坛

C++PrimerPlus习题及答案-第六章-免费源码丞旭猿

习题选自:C++ Primer Plus(第六版)内容仅供参考,如有错误,欢迎指正 !


1.简单文件输入/输出(写入到文本文件中)对于文件输入,C++使用类似于cout的东西。对于cout,需要包含iostream头文件,该头文件定义了一个用于输出的ostream类,并且在该头文件中声明了一个cout的ostream变量(对象)。而在使用到文本写入文件时,需要包含头文件fstream,该头文件定义了一个ofstream类,使用的时候需要声明一个ofstream类,声明完成后需要通过open()方法将声明的对象与文件关联起来,例如:ofstream outFile;outFile.open("filename.txt");然后就可以像使用cout一样使用该ofstream对象。将在屏幕上打印的数据信息,存储到文件中去。最后使用close()方法将其关闭。

  • cout<<fixedoutFile<<fixed用一般的方式输出浮点型,例如C++程序在控制台显示大一点的数,显示的时候使用了科学计数法,使用该命令即可像一般的方式显示。

  • cout.precision(2)outFile.precision(2)设置精确度为2,并返回上一次的设置。

  • cout.setf(iOS_base::showpoint)outFile.setf(iOS_base::showpoint)显示浮点数小数点后面的零。

2.简单文件输入/输出(读取文本文件)对于文件读取,同样的,C++使用类似cin的东西。对于cin,需要包含iostream头文件,该文件定义了一个用于输入的istream类,并在该头文件中已经声明好了一个cin的istream变量(对象)。而在使用读取文件时,需要包含fstream头文件,该头文件定义了ifostream类,在使用的时候需要声明一个ifstream类,通过open()方法与文件关联起来,然后就可以像使用cin一样使用该ifstream,读取目标文件的内容。最后,使用close()方法将文件关闭。

  • 可以结合ifstream对象和运算符>>来读取各种类型的数据。

  • 可以使用ifstream对象与get()方法读取一个字符,使用getline()来读取一行字符。

  • 可以结合使用ifstream与eof()、fail()等方法判断输入是否成功。

复习题

1.请看下面两个计算空格和换行符数目的代码片段:

1//version 12while(cin.get(ch))//quit on eof3{4if(ch==)5spaces++;6if(ch==\n)7newlines++;8}910//version 211while(cin.get(ch))//quit eof12{13if(ch==)14spacees++;15elseif(ch==\n)16newlines++;17}

第二个格式比第一个格式好在哪里?

第二个版本比第一个版本效率更高,因为在第一个中对于每个字符都需要判断两次,而在第二个版本中,如果字符为空格,在经过if判断确定为空格后,该字符肯定不是换行符,第二个else if的判断直接跳过,节省判断时间。

2.在程序清单6.2中,用ch+1替换++ch将发生什么情况?

程序清单6.2 ifelse.cpp

1// ifelse.cpp -- using the if else statement2include3intmain()4{5charch;6std::cout<<"Type, and I shall repeat.\n";7std::cin.get(ch);8while(ch !=.)9{10if(ch ==\n)11std::cout<< ch;// done if newline12else13std::cout<< ++ch;// done otherwise14std::cin.get(ch);15}16// try ch + 1 instead of ++ch for interesting effect17std::cout<<"\nPlease excuse the slight confusion.\n";18// std::cin.get();19// std::cin.get();20return0;21}

++ch的数据类型依旧是char型,但对于char+1最终类型为int型,因此当++ch换成ch+1后,输出的是数字。

3.请认真考虑下面的程序:

1include2usingnamespacestd;3intmain()4{5charch;6intct1,ct2;7ct1=ct2=0;8while((ch=cin.get())!=$)9{10cout<11ct1++;12if(ch=$)13ct2++;14cout<15}16cout<<"ct1="<",ct2="<"\n";17return0;18}

假设输入如下(请在每行末尾按回车键):

Hi!Send $10 or $20 now!

则输出将是什么(还记得吗,输入被缓冲)?

输入输出结果为

1Hi!2H$i$!$3$Send $10or$20 now!4S$e$n$d$ $ct1=9,ct2=9

由于程序中使用的是ch=$,所以每次循环该if条件内代码都执行一次,因此ct1与ct2相等。同时在输入Hi!之后键入回车,因此在读取回车之后,打印出来,光标换行,紧接着打印$。

4.创建表示下述条件的逻辑表达式:

a.weight大于或等于115,但小于125。b.ch为q或Q。c.x为偶数,但不是26.d.x为偶数,但不是26。e.donation为1000-2000或guest为1。f.ch是小写字母或大写字母(假设小写字母是依次编码的,大写字母也是依次编码的,但在大小写字母间编码是不连续的)。

1//a2weight>=115&& weight<12534//b5ch==q|| ch==Q67//c8x%2==0&& x!=26910//d11x%2==0&& x%26!=01213//e14donation>=1000&& donation<=20000|| guest==11516//f17(ch>=a&& ch<=z) || (ch<=Z&& ch>=A)

5.在英语中,”I will not not speak(我不会不说) “的意思与”I will speak(我要说)”相同。在c++中,!!x是否与x相同呢?

对于bool变量而言,!!x与x是相同的,但对于其他类型变量不一定相同,例如!!5=1,!!5≠5。

6.创建一个条件表达式,其值为变量的绝对值。也就是说,如果变量x为正,则表达式的值为x;但如果x为负,则表达式的值为-x–这是一个正值。

1x>=0? x : -x;

7.用switch改写下面的代码片段:

1if(ch==A)2a_grade++;3elseif(ch==B)4b_grade++;5elseif(ch==C)6c_grade++;7elseif(ch==D)8d_grade++;9else10f_grade++;

改写后代码:

1switch(ch)2{3caseA: a_grade++;4break;5caseB: b_grade++;6break;7caseC: c_grade++;8break;9caseD: d_grade++;10break;11default:   f_grade++;12break;13}

8.对于程序清单6.10,与使用字符(如a和c)表示菜单选项和case标签有何优点呢?(提示:想一想用户输入q和输入5的情况。)

程序清单6.10 switch.cpp

1// switch.cpp -- using the switch statement2include3usingnamespacestd;4voidshowmenu();// function prototypes5voidreport();6voidcomfort();7intmain()8{9showmenu();10intchoice;11cin>> choice;12while(choice !=5)13{14switch(choice)15{16case1:cout<<"\a\n";17break;18case2: report();19break;20case3:cout<<"The boss was in all day.\n";21break;22case4: comfort();23break;24default:cout<<"Thats not a choice.\n";25}26showmenu();27cin>> choice;28}29cout<<"Bye!\n";30return0;31}32voidshowmenu()33{34cout<<"Please enter 1, 2, 3, 4, or 5:\n"35"1) alarm 2) report\n"36"3) alibi 4) comfort\n"37"5) quit\n";38}39voidreport()40{41cout<<"Its been an excellent week for business.\n"42"Sales are up 120%. Expenses are down 35%.\n";43}44voidcomfort()45{46cout<<"Your employees think you are the finest CEO\n"47"in the industry. The board of directors think\n"48"you are the finest CEO in the industry.\n";49}

使用数字作为菜单选项和case标签,限定了用户只有输入数字的时候才能有效,若用户错误的输入非整数类型,导致程序被挂起。而使用字符作为菜单选项和case标签,当用户输入错误类型,程序能正确通过default部分提示用户输入错误,用户体验更加友好,提高了程序的容错性和健壮性。

9.请看下面的代码片段

1intline =0;2charch;3while(cin.get(ch))4{5if(ch==Q)6break;7if(ch!=\n)8continue;9line++;10}

重写后代码:

1intline =0;2charch;3while(cin.get(ch) && ch!=Q)4{5if(ch==\n)6line++;7}

编程练习

1.编写一个程序,读取键盘输入,直到遇到@符号为止,并回显输入(数字除外),同时将大写字符转换为小写字符,将小写字符转换为大写(别忘了cctype函数系列)

1include2include3usingnamespacestd;45intmain()6{7cout<<"Please enter characters (type @ to stop):";8charch;9cin.get(ch);10while(ch !=@)11{12if(islower(ch))13ch =toupper(ch);14elseif(isupper(ch))15ch =tolower(ch);16if(!isdigit(ch))17cout<< ch;18cin.get(ch);19}20system("pause");21return0;22}

2.编写一个程序,最多将10个donation值读入一个double数组中(如果你愿意,也可以使用模板类array)。程序遇到非数字输入时将结束输入,并报告这些数字的平均值以及数组中有多少个数字大于平均值。

1include2include3usingnamespacestd;4intmain()5{6array<double,10>donations;7doublesum=0;8cout<<"Please enter donation(non-number to stop):";9inti;10doubledonation;11for(i=0;(i<10)&&(cin>>donation);++i)12{13donations[i]=donation;14sum=+donations[i];15}1617doubleavg=sum/(i+1);18cout<<"Average:"<endl;19cout<<"Number larger than average:";20for(intj=0;j21{22if(donations[j]>avg)23cout<" ";24}25cout<<endl;26return0;27}

3.编写一个菜单驱动程序的雏形。该程序显示一个提供四个选项的菜单–每个选项用一个字母表标记。如果用户使用有效选项之外的字母进行响应,程序将提示用户输入有效的字母,直到用户这样选择为止。然后,该程序使用一条switch语句,根据用户的选择执行一个简单操作。该程序的运行情况如下:

1Please enter oneofthe following choices:2c) carnivore         p) pianist3t) tree                  g)game4f5Please enter a c,p,torg:q6Please enter a c,p,torg:t7A mapleisa tree.

代码实现:

1include2usingnamespacestd;3intmain()4{5cout<<"Please enter one of the following choices:"<<endl;6cout<<"c) carnivore         p) pianist"<<endl;7cout<<"t) tree              g) game"<<endl;8charch;9cin>>ch;10while(ch!=c&& ch!=p&& ch!=t&& ch!=g)11{12cout<<"Please enter a c,p,t or g:";13cin>>ch;14}15switch(ch)16{17casec:18cout<<"A maple is a carnivore."<<endl;19break;20casep:21cout<<"A maple is a pianist."<<endl;22break;23caset:24cout<<"A maple is a tree."<<endl;25break;26caseg:27cout<<"A maple is a game."<<endl;28break;29default:30break;31}32return0;33}

4.加入Benevolent Order of Programmer后,在BOP大会上,人们便可以通过加入者的真实姓名、头衔或秘密BOP姓名来了解他(她)。请编写一个程序,可以使用真实姓名、头衔、秘密姓名或成员偏好来列出成员。编写该程序时,请使用下面的结构:

1//Benevolent Order of Programmers name structure2structbop{3charfullname[strsize];//real name4chartitle[strzie];//job title5charbopname[strsize];//secret BOP name6intpreference;//0=fullname,1=title,2=bopname7};

该程序创建一个由上述结构组成的小型数组,并将其初始化为适当的值。另外,该程序使用一个循环,让用户在下面的选项中进行选择:

1a.display by name        b.diaplay by title2c.display by bopname     d.display by preference3q.quit

注意,display by preference并不意味显示成员的偏好,而是意味着根据成员的偏好来列出成员。例如,如果偏好号为1,则选择d将显示程序员的头衔。该程序的运行情况如下:

1Benevolent Order of Programmers Report2a. display by name         b. display by title3c. display by bopname      d. display by preference4q. quit5Enter your choice: a6Wimp Macho7Raki Rhodes8Celia Laiter9Hoppy Hipman10Pat Hand11Next choice: d12Wimp Macho13Junior Programmer14MIPS15Analyst Trainee16LOOPY17Next choice: q18Bye!

代码实现 :

1include23usingnamespacestd;45constintstrsize =20;6structbop7{8charfullname[strsize];9chartitle[strsize];10charbopname[strsize];11intpreference;//0 = fullname, 1 = title, 2 = bopname12};1314intmain()15{16intprogrammerNum =5;17bop programmers[programmerNum]={{"Wimp Macho","Junior Programmer","WM",0},18{"Raki Rhodes","Junior Programmer","RR",1},19{"Celia Laiter","Junior Programmer","MIPS",2},20{"Hoppy Hipman","Analyst Trainee","HH",1},21{"Pat Hand","Junior Programmer","LOOPY",2}};22cout<<"Benevolent Order of Programmers Report"<<endl;23cout<<"a. display by name          b. display by title"<<endl;24cout<<"c. display by bopname       d. display by preference"<<endl;25cout<<"q. quit"<<endl;26cout<<"Enter your choice: ";27charchoice;28while(cin.get(choice))29{30if(choice ==a)31{32for(inti =0; i < programmerNum; i++)33{34cout<< programmers[i].fullname <<endl;35}36}37elseif(choice ==b)38{39for(inti =0; i < programmerNum; i++)40{41cout<< programmers[i].title <<endl;42}43}44elseif(choice ==c)45{46for(inti =0; i < programmerNum; i++)47{48cout<< programmers[i].bopname <<endl;49}50}51elseif(choice ==d)52{53for(inti =0; i < programmerNum; i++)54{55if(programmers[i].preference ==0)56{57cout<< programmers[i].fullname <<endl;58}59elseif(programmers[i].preference ==1)60{61cout<< programmers[i].title <<endl;62}63else64{65cout<< programmers[i].bopname <<endl;66}67}68}69elseif(choice ==q)70{71cout<<"Bye!"<<endl;72break;73}74else75{76if(choice ==\n)77{78continue;79}80cout<<"input error, please re-enter!"<<endl;81}82cout<<"Next choice: ";83}8485return0;86}

5.在Neutronia王国,货币单位是tvarp,收入所得税的计算方式如下:

5000 tvarps: 不收税5001~15000 tvarps: 10%15001~35000 tvarps: 15%35000 tvarps以上: 20%

例如,收入为38000 tvarps时,所得税为5000×0.00+10000×0.10+2000×0.15+3000×0.20,即 4600tvarps。请编写一个程序,使用循环来要求用户输入收入,并报告所得税,当用户输入负数或非数字时,循环将结束。

代码实现:

1include23usingnamespacestd;45intmain()6{7cout<<"Please enter your income(if you enter negative number or non-numberic, it will exit.) : ";8doubleincome, tax;9while(cin>> income)10{11cout<< income <<endl;12if(income >35000)13{14tax =10000*0.10+20000*0.15+ (income -35000) *0.20;15}16elseif(income >=15001)17{18tax = (income -3500) *0.15+10000*0.10;19}20elseif(income >=5001)21{22tax = (income -5000) *0.10;23}24elseif(income >=0)25{26tax =0;27}28else29{30cout<<"Enter negative number, exiting soon..."<<endl;31break;32}33cout<<"your should pay tax : "<< tax <<" tvarps."<<endl;34cout<<"Please enter another income(if you enter negative number or non-numberic, it will exit.) : ";35}36cout<<"Exited, Bye !"<<endl;37return0;38}

6.编写一个程序,记录捐助给”维护合法权利团体”的资金。该程序要求用户输入捐赠者数目,然后要求用户输入每一个捐献者的姓名和款项。这些信息被存储在一个动态分配的结构数组中.每个数据结构有两个成员:用来存储姓名的字符串数组(或string对象)和用来存储款项的double成员。读取所有的数据后,程序将显示所有捐款超过10000的捐款着姓名及其捐款数额。该列表前应包含一个标题,指出下面的捐款者是重要捐款人(Grand Patrons)。然后,程序将列出其他的捐款者,该列表要以Partons开头。如果某种类别没有捐款者,则程序将打印单词”none”。该程序只显示这两种类别,而不进行排序。

代码实现:

1include2include34usingnamespacestd;56structDonationInfo{7stringname;8doubleamount;9};1011voiddonationInfoDisplay(DonationInfo donationInfo[],intnum,boolisGrandPatrons)12{13intcountNum =0;14for(inti =0; i < num ; i++)15{16if(isGrandPatrons)17{18if(donationInfo[i].amount >10000)19{20countNum++;21cout<< donationInfo[i].name  <<endl;22}23}24else25{26if(donationInfo[i].amount <=10000)27{28countNum++;29cout<< donationInfo[i].name  <<endl;30}31}32}33if(countNum ==0)34cout<<"none"<<endl;35}3637intmain()38{39cout<<"Please enter the number of donors :";40intnum;41while(!(cin>> num))42{43cin.clear();44cin.sync();45cin.ignore();46cout<<"***[WARNING]:Please enter positive integer.***"<<endl;47cout<<"Please enter the number of donors :";48}49DonationInfo* donationInfo =newDonationInfo[num];50for(inti =0; i < num; i++)51{52cout<<"enter the donor name :";53cin>> donationInfo[i].name;54cout<<"enter the donation amount :";55cin>> donationInfo[i].amount;56}57cout<<"******Grand Partons******"<<endl;58donationInfoDisplay(donationInfo, num,true);59cout<<"******Partons******"<<endl;60donationInfoDisplay(donationInfo, num,false);6162delete[] donationInfo;63return0;64}

7.编写一个程序,它每次读取一个单词,直到用户只输入q。然后,该程序指出有多少个单词以元音打头,有多少个单词以辅音打头,还有多少个单词不属于这两类。为此,方法之一是,使用isalpha()来区分以字母和其他字母打头的单词,然后对于通过isalpha()测试的单词,使用if或switch语句来确定哪些以元音打头。该程序的运行情况如下:

Enter words (q to quit):The 12 awesome oxem ambledquiety across 15 meters of lawn. q5 words beginning with vowels4 words beginning with consonants2 others

代码实现:

1include2include3usingnamespacestd;45intmain()6{7cout<<"Enter words (q to quit) :"<<endl;8stringword;9intvowelNum =0;10intconsonantNum =0;11intothersNum =0;12while(cin>> word)13{14if(word =="q")15{16break;17}18else19{20if(isalpha(word[0]))21{22switch(word[0])23{24casea:25casee:26casei:27caseo:28caseu:29caseA:30caseE:31caseI:32caseO:33caseU:34vowelNum++;35break;36default:37consonantNum++;38}39}40else41{42othersNum++;43}44}45}46cout<< vowelNum <<" words beginning with vowels"<<endl;47cout<< consonantNum <<" words beginning with consonants"<<endl;48cout<< othersNum <<" others"<<endl;49return0;50}

8.编写一个程序,他打开一个文件,逐个字地读取该文件,直到到达文件末尾,然后指出该文件中包含多少个字符。

代码实现:

1include2include34usingnamespacestd;56intmain()7{8ifstream txtSource;9txtSource.open("test.txt", ios::in);10if(!txtSource.is_open())11{12cout<<"File failed to open !"<<endl;13exit(EXIT_FAILURE);14}15charch;16intcharacterNum =0;17while(txtSource >> ch)18{19characterNum++;20}21if(txtSource.eof())22cout<<"End of file reached.\n";23elseif(txtSource.fail())24cout<<"Input terminated by data mismatch."<<endl;25else26cout<<"Input terminated for unknown reason."<<endl;27if(characterNum ==0)28cout<<"No data processed."<<endl;29else30cout<<"The file contains "<< characterNum <<" characters"<<endl;3132txtSource.close();33return0;34}

9.完成编程练习6,但从文件中读取所需的信息。该文件的第一项应为捐款人数,余下的内容应为对的行。在每一对中,第一行为捐款人姓名,第二行为捐款数额。即该文件类似于下面:

代码实现:

1include2include3include45usingnamespacestd;67structDonationInfo{8stringname;9doubleamount;10};1112voiddonationInfoDisplay(DonationInfo donationInfo[],intnum,boolisGrandPatrons)13{14intcountNum =0;15for(inti =0; i < num ; i++)16{17if(isGrandPatrons)18{19if(donationInfo[i].amount >10000)20{21countNum++;22cout<< donationInfo[i].name  <<endl;23}24}25else26{27if(donationInfo[i].amount <=10000)28{29countNum++;30cout<< donationInfo[i].name  <<endl;31}32}33}34if(countNum ==0)35cout<<"none"<<endl;36}3738intmain()39{40cout<<"Read file content..."<<endl;41ifstream txtDonationInfo;42txtDonationInfo.open("test.txt", ios::in);43if(!txtDonationInfo.is_open())44{45cout<<"File failed to open !"<<endl;46exit(EXIT_FAILURE);47}48intnum =0;49(txtDonationInfo >> num).get();50DonationInfo* donationInfo =newDonationInfo[num];51for(inti =0; i < num; i++)52{53txtDonationInfo >> donationInfo[i].name;54txtDonationInfo >> donationInfo[i].amount;55}56cout<<"******Grand Partons******"<<endl;57donationInfoDisplay(donationInfo, num,true);58cout<<"******Partons******"<<endl;59donationInfoDisplay(donationInfo, num,false);6061delete[] donationInfo;62txtDonationInfo.close();63return0;64}
举报/反馈

声明:本文部分素材转载自互联网,如有侵权立即删除 。

© 版权声明
THE END
喜欢就支持一下吧
点赞0赞赏 分享
相关推荐
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容