C++primer中文版第四版习题答案word版本第八章.doc
文本预览下载声明
第八章 标准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;
}
显示全部