面向对象的C++程序设计 第六版 课后习题答案第六章.pdf
Chapter6
I/OSTREAMSASANINTRODUCTIONTOOBJECTSANDCLASSES
1.SolutionstoSelectedProgrammingProblems.
Mostoftheproblemstatementsareinprogramcomments.Iputanabbreviatedproblem
statementinthesourcefileforeachproblemandIrequiremystudentstodothisto.It
savestheirtime(andmytimeaswe)byforcingtheproblemstatementthroughtheir
mindsatleastonce.(Thatsthetheory,atleast.)
Theiostreamsclasses,theirbaseclassesandsiblingclassesahavememberfunctions
(destructors)thatwiclosethefilesautomaticaywhenthefilevariablegoesoutofscope.
Torereadthefile,itistheprogrammerstasktocloseandreopenthefile.
1.Max-Min
Problem:Searchafileofnumbersoftypeintandwritethelargestandsmaesttothe
screen.Thefileisspaceandnewlinedelimitedintegers.Instructorsuppliesthedatafile.
//File:ch6prob1.cc
//Task:readuptoEOF,keeplargest,smaest,outputto
//screen
//Outline:
//initializelargestto-maxint
//andinitializesmaesttomaxint,thisrequiresclimits
//
//openfile,checkforOKstatus
//
//while(notEOFoninput)
//getanint
//if(inputlargest)
//largest=input;
//if(inputsmaest)
1
Copyright©2007PearsonEducation,Inc.PublishingasPearsonAddison-Wesley
SavitchInstructorsResourceGuide
ProblemSolvingw/C++,6eChapter6
//smallest=input;
//
//outputlargest,smallest,withappropriatelabeling.
//Discussion:youcaneitherdosomeresearchonyoursystem,
//useclimits,oryoucanchoosealargestvaluelarger
//thanthelargestinyourfile,andanalogouslyfor
//smallest.Ifyourcompilerusestwobyteintegers,then
//theinitialvalueforfindingthesmallestwillbe
//2^15-1=32,7