- 15
- 0
- 约9.34千字
- 约 11页
- 2018-06-20 发布于河南
- 举报
Cprimer中文版第四版习题答案word版本第八章
第八章 标准IO库
8.1 假设os是一个ofstream对象,下面程序做了什么?
os “Goodbye!” endl;
如果os 是ostringstream对象呢? 或者,os 是ifstream对象呢?
答:第一个,向文件中写入“Goodbye”, 第二个向string对象中写入“Goodbye”,第三个,如果os是一个ifstream对象,则错误,因为ifstream类中没有定义操作符 。
8.2 下面的声明是错误的,指出其错误并改正之: ostream print(ostream os);
答:标准库类型不允许做复制或赋值操作。形参或返回类型不能为流类型,所以上句代码错误,因为它把流类型的对象当做了形参。应改为传递指向该对象的指针或引用:
ostream print( ostream os );
8.3 编写一个函数,其唯一的形参和返回值都是istream类型。该函数应一直读取流直到到达文件的结束符为止,还应将读到的内容输出到标准输出中。最后,重设流使其有效,并返回该流。
答:
// 定义控制台??应用程序的入口点。
//
#include stdafx.h
#include stdafx.h
#include iostream
using namespace std;
istream f( istream in )
{
int ival;
while ( in ival, !in.eof()) // 遇到文件结束符之前一直读入数据
{
if(in.bad()) // input stream is corrupted; bail out, 流是否已被破坏
throw runtime_error(IO stream corrupted);
if ( in.fail() ) // bad input
{cerr bad date, try again:;
in.clear( ); // reset the stream
in.setstate(istream::eofbit); // 结束死循环
continue;
}
// process input
cout ival endl;
}
in.clear(); // 将n中的所有状态值都设为有效状态
return in;
}
int main()
{
cout Input some words ( ctrl + z to end ):\n;
f( cin );
system(pause);
return 0;
}
8.4 通过cin为实参实现调用来测试上题编写的函数。
8.5 导致下面的while循环终止的原因是什么?
while ( cin i ) //….
答:遇到了结束符;或者遇到了系统故障;读入了无效数据。
8.6 由于ifstream继承了istream,因此可将ifstream对象传递给形参为istream引用的函数。使用8.2节第一个习题编写的函数读取已命名的文件。
// 8.6.cpp : 定?§义°?控?制?台??§应?|用??程¨?序¨°的ì?入¨?口¨2点ì?。?ê
//
#include stdafx.h
#include iostream
#include fstream
#include string
using namespace std;
istream f( istream is )
{
//int ival;
string ival;
while ( is ival, !is.eof()) // 遇??到ì?文?件t结¨¢束o?符¤?之?前??一°?直?à读¨¢入¨?数oy据Y
{
if(is.bad()) // input stream is corrupted; bail out, 流¢??是o?否¤?已°?被à?破?坏|ì
throw runtime_error(IO stream corrupted);
if ( is.fail() ) // bad input
{
cerr bad data, try again.;
is.clear( ); // reset the stream
is.setstate(istream::eofbit); // 结¨¢束o?死¨¤循-环?¤
continue;
}
您可能关注的文档
- 14.4课题学习第一课时n.ppt
- 1接口技术讲义(第一章_接口技术概述.).doc
- 2011年下学期九年级物理第二次月考试卷.doc
- 2012第五周理综物理试题档.doc
- C语言ppt教案07.ppt
- F119发动机全称F119.doc
- eViewHMI常见问题库.doc
- HF(高粘度指数液压油).ppt
- §1.1.1长度和的测量.doc
- theBritishIsles-七中.ppt
- 小区绿化施工协议书.docx
- 墙面施工协议书.docx
- 1 古诗二首(课件)--2025-2026学年统编版语文二年级下册.pptx
- (2026春新版)部编版八年级道德与法治下册《3.1《公民基本权利》PPT课件.pptx
- (2026春新版)部编版八年级道德与法治下册《4.3《依法履行义务》PPT课件.pptx
- (2026春新版)部编版八年级道德与法治下册《6.2《按劳分配为主体、多种分配方式并存》PPT课件.pptx
- (2026春新版)部编版八年级道德与法治下册《6.1《公有制为主体、多种所有制经济共同发展》PPT课件.pptx
- 初三教学管理交流发言稿.docx
- 小学生课外阅读总结.docx
- 餐饮门店夜经济运营的社会责任报告(夜间贡献)撰写流程试题库及答案.doc
原创力文档

文档评论(0)