ITEEDU

11.5 成员函数read、gcount和write的无格式输入/输出

调用成员函数read、write可实现无格式输入/输出。这两个函数分别把一定量的字节写入字符数组和从字符数组中输出。这些字节都是未经任何格式化的,仅仅是以原始数据形式输入或输出。

例如:

char buffe[] ="HAPPY BIRTHDAY";
cout.write(buffer, 10 );

输出buffet的10个字节(包括终止cout和<<输出的空字符)。因为字符串就是第一个字符的地址,所以函数调用:

cout.write("ABCDEFGHIJKLMNOPQRSTUVWXYZ",10);

显示了字母表中的前10个字母。

成员函数read把指定个数的字符输入到字符数组中。如果读取的字符个数少于指定的数目,可以设置标志位failbit(见11.8节)。

成员函数gcount统计最后输入的字符个数。

图11.15中的程序演示了类istream中的成员函数read和gcount,以及类ostream中的成员函数write。程序首先用函数read向字符数组buffer中输入20个字符(输入序列比字符数组长),然后用函数gcount统计所输入的字符个数,最后用函数write输出buffer中的字符。

  // Fig. 11.15: fig11_15.cpp
 // Unformatted I/O with read, gcount and write.
 #include < iostream.h>
 int main()
 {
   const int SIZE = 80;
   char buffer[ SIZE ];
  cout << "Enter a sentence:\n";
  cin.read( buffer, 20 );
  cout << "\nThe sentence entered was:\n";
  cout.write( buffer, cin.gcount() );
  cout << endl;
  return 0;
 }

输出结果:

Enter a sentence:

Using the read, write, and gcount member functions

The sentence entered was:

Using the read,write

图 11.15 成员函数read,gcount和write的无格式I/O

11.6 流操纵算子:

C++提供了大量的用于执行格式化输入/输出的流操纵算子。流操纵算子提供了许多功能,如设置域宽、设置精度、设置和清除格式化标志、设置域填充字符、刷新流、在输出流中插入换行符并刷新该流、在输出流中插入空字符、跳过输入流中的空白字符等等。下面几节要介绍这些特征。

11.6.1 整数流的基数:流操纵算子dec、oct、hex和setbase

整数通常被解释为十进制(基数为10)整数。如下方法可改变流中整数的基数:插人流操纵算子hex可设置十六进制基数(基数为16)、插人流操纵算子oct可设置八进制基数(基数为8)、插人流操纵算子dec可恢复十进制基数。

也可以用流操纵算子setbace来改变基数,流操纵算于setbase带有一个整数参数10、8或16。因为流操纵算子setbase是带有参数的,所以也称之为参数化的流操纵算子。使用setbose或其他任何参数化的操纵算子都必须在程序中包含头文件iomanip.h。如果不明确地改变流的基数,流的基数是不变的。图11.16中的程序示范了流操纵算子hex、oct、dec和setbase的用法。

// Fig. 11.16: fig11_16.cpp
 // Using hex, oct, dec and setbase stream manipulators.
 #include < iostream.h>
 #include < iomanip.h>
 int main()
{
   int n;
  cout << "Enter a decimal number: ";
  cin >> n;
  cout << n << "in hexadecimal is:"
      << hex << n << '\n'
      << dec << n << "in octal is:"
      << oct << n << '\n'
      << setbase( 10 ) << n <<" in decimal is:"
      << n << endl;
  return 0;
 }  

输出结果:

Enter a decimal number: 20

20 in hexadecimal is: 14

20 in octal is: 24

20 in decimal is: 20

图 11.16 使用流操纵算子hex、oct、dec和setbase