Chinaunix首页 | 论坛 | 博客
  • 博客访问: 487496
  • 博文数量: 77
  • 博客积分: 1047
  • 博客等级: 少尉
  • 技术积分: 898
  • 用 户 组: 普通用户
  • 注册时间: 2011-08-25 17:16
文章分类

全部博文(77)

文章存档

2016年(2)

2013年(2)

2012年(33)

2011年(40)

分类: C/C++

2011-10-22 15:43:25

作者:管宁

      iostream为内置类型类型对象提供了输入输出支持,同时也支持文件的输入输出,类的设计者可以通过对iostream库的扩展,来支持自定义类型的输入输出操作。

      为什么说要扩展才能提供支持呢?我们来一个示例。

    1. #include <stdio.h>
    2. #include <iostream>
    3. using namespace std;
    4. class Test
    5. {
    6.  public:
    7.   Test(int a=0,int b=0)
    8.   {
    9.    Test::a=a;
    10.    Test::b=b;
    11.   }
    12.   int a;
    13.   int b;
    14. };
    15. int main()
    16. {
    17.  Test t(100,50);
    18.  printf("%???",t);//不明确的输出格式
    19.  scanf("%???",t);//不明确的输入格式
    20.  cout<<t<<endl;//同样不够明确
    21.  cin>>t;//同样不够明确
    22.  system("pause");
    23. }
      由于自定义类的特殊性,在上面的代码中,无论你使用c风格的输入输出,或者是c++的输入输出都不是不明确的一个表示,由于c语言没有运算符重载机制,导致stdio库的不可扩充性,让我们无法让printf()和scanf()支持对自定义类对象的扩充识别,而c++是可以通过运算符重载机制扩充 iostream库的,使系统能能够识别自定义类型,从而让输入输出明确的知道他们该干什么,格式是什么。

      在上例中我们之所以用printf与cout进行对比目的是为了告诉大家,C与C++处理输入输出的根本不同,我们从c远的输入输出可以很明显看出是函数调用方式,而c++的则是对象模式,cout和cin是ostream类和istream类的对象。

      我们所熟悉的输入输出操作分别是由istream(输入流)和ostream(输出流)这两个类提供的,为了允许双向的输入/输出,由istream和ostream派生出了iostream类。

      类的继承关系见下图:
    C++的iostream标准库介绍 - Elivans - Elivans的博客

    iostream库定义了以下三个标准流对象:

    1. cin,表示标准输入(standard input)的istream类对象。cin使我们可以从设备读如数据。
    2. cout,表示标准输出(standard output)的ostream类对象。cout使我们可以向设备输出或者写数据。
    3. cerr,表示标准错误(standard error)的osttream类对象。cerr是导出程序错误消息的地方,它只能允许向屏幕设备写数据。

      输出主要由重载的左移操作符(<<)来完成,输入主要由重载的右移操作符(>>)完成:

    1. >>a表示将数据放入a对象中。
    2. <

      这些标准的流对象都有默认的所对应的设备,见下表:

    cin 键盘 stdin 标准输入
    cout 显示器屏幕 stdout 标准输出
    cerr 显示器屏幕 stderr 标准错误输出
      上表中的意思表明cin对象的默认输入设备是键盘,cout对象的默认输出设备是显示器屏幕。

      那么原理上C++有是如何利用cin/cout对象与左移和右移运算符重载来实现输入输出的呢?

      下面我们以输出为例,说明其实现原理:

    1. cout是ostream类的对象,因为它所指向的是标准设备(显示器屏幕),所以它在iostream头文件中作为全局对象进行定义。
    2. ostream cout(stdout);//其默认指向的C中的标准设备名,作为其构造函数的参数使用。
    3. 在iostream.h头文件中,ostream类对应每个基本数据类型都有其友元函数对左移操作符进行了友元函数的重载。
      • ostream& operator<<(ostream &temp,int source);
      • ostream& operator<<(ostream &temp,char *ps);
      • ... 等等

      一句输出语句:cout<<"www.cndev-lab.com";,事实上调用的就是ostream& operator<<(ostream &temp,char *ps);这个运算符重载函数,由于返回的是流对象的引用,引用可以作为左值使用,所以当程序中有类似cout<<"www.cndev- lab.com"<<"中国软件开发实验室";这样的语句出现的时候,就能够构成连续输出。

      由于iostream库不光支持对象的输入输出,同时也支持文件流的输入输出,所以在详细讲解左移与右移运算符重载只前,我们有必要先对文件的输入输出以及输入输出的控制符有所了解。

    由于文件设备并不像显示器屏幕与键盘那样是标准默认设备,所以它在fstream.h头文件中是没有像cout那样预先定义的全局对象,所以我们必须自己定义一个该类的对象,我们要以文件作为设备向文件输出信息(也就是向文件写数据),那么就应该使用ofstream类。

      ofstream类的默认构造函数原形为:

      ofstream::ofstream(const char *filename,int mode = ios::out,int openprot = filebuf::openprot);
    • filename:  要打开的文件名
    • mode:    要打开文件的方式
    • prot:    打开文件的属性

      其中mode和openprot这两个参数的可选项表见下表:

    mode属性表
    ios::app 以追加的方式打开文件
    ios::ate 文件打开后定位到文件尾,ios:app就包含有此属性
    ios::binary 以二进制方式打开文件,缺省的方式是文本方式。两种方式的区别见前文
    ios::in 文件以输入方式打开
    ios::out 文件以输出方式打开
    ios::trunc 如果文件存在,把文件长度设为0
      可以用“或”把以上属性连接起来,如ios::out|ios::binary。
    openprot属性表
    属性 含义
    0 普通文件,打开访问
    1 只读文件
    2 隐含文件
    4 系统文件
      可以用“或”或者“+”把以上属性连接起来 ,如3或1|2就是以只读和隐含属性打开文件。

    实例代码如下:

    1. #include <fstream>
    2. using namespace std;
    3. int main()
    4. {
    5.     ofstream myfile("c:\\1.txt",ios::out|ios::trunc,0);
    6.     myfile<<"中国软件开发实验室"<<endl<<"网址:"<<"www.cndev-lab.com";
    7.     myfile.close();
    8.     system("pause");
    9. }
      文件使用完后可以使用close成员函数关闭文件。

      ios::app为追加模式,在使用追加模式的时候同时进行文件状态的判断是一个比较好的习惯。

      示例如下:

    1. #include <iostream>
    2. #include <fstream>
    3. using namespace std;
    4. int main()
    5. {
    6.     ofstream myfile("c:\\1.txt",ios::app,0);
    7.     if(!myfile)//或者写成myfile.fail()
    8.     {
    9.         cout<<"文件打开失败,目标文件状态可能为只读!";
    10.         system("pause");
    11.         exit(1);
    12.     }
    13.     myfile<<"中国软件开发实验室"<<endl<<"网址:"<<"www.cndev-lab.com"<<endl;
    14.     myfile.close();
    15. }
      在定义ifstream和ofstream类对象的时候,我们也可以不指定文件。以后可以通过成员函数open()显式的把一个文件连接到一个类对象上。

      例如:

    1. #include <iostream>
    2. #include <fstream>
    3. using namespace std;
    4. int main()
    5. {
    6.     ofstream myfile;
    7.     myfile.open("c:\\1.txt",ios::out|ios::app,0);
    8.     if(!myfile)//或者写成myfile.fail()
    9.     {
    10.         cout<<"文件创建失败,磁盘不可写或者文件为只读!";
    11.         system("pause");
    12.         exit(1);
    13.     }
    14.     myfile<<"中国软件开发实验室"<<endl<<"网址:"<<"www.cndev-lab.com"<<endl;
    15.     myfile.close();
    16. }
      下面我们来看一下是如何利用ifstream类对象,将文件中的数据读取出来,然后再输出到标准设备中的例子。

      代码如下:

    1. #include <iostream>
    2. #include <fstream>
    3. #include <string>
    4. using namespace std;
    5. int main()
    6. {
    7.     ifstream myfile;
    8.     myfile.open("c:\\1.txt",ios::in,0);
    9.     if(!myfile)
    10.     {
    11.         cout<<"文件读错误";
    12.         system("pause");
    13.         exit(1);
    14.     }
    15.     char ch;
    16.     string content;
    17.     while(myfile.get(ch))
    18.     {
    19.         content+=ch;
    20.         cout.put(ch);//cout<<ch;这么写也是可以的
    21.     }
    22.     myfile.close();
    23.     cout<<content;
    24.     system("pause");
    25. }
      上例中,我们利用成员函数get(),逐一的读取文件中的有效字符,再利用put()成员函数,将文件中的数据通过循环逐一输出到标准设备(屏幕)上, get()成员函数会在文件读到默尾的时候返回假值,所以我们可以利用它的这个特性作为while循环的终止条件,我们同时也在上例中引入了C++风格的字符串类型string,在循环读取的时候逐一保存到content中,要使用string类型,必须包含string.h的头文件。

    我们在简单介绍过ofstream类和ifstream类后,我们再来看一下fstream类,fstream类是由iostream派生而来,fstream类对象可以同对文件进行读写操作。

      示例代码如下:

    1. #include <iostream>
    2. #include <fstream>
    3. using namespace std;
    4. int main()
    5. {
    6.     fstream myfile;
    7.     myfile.open("c:\\1.txt",ios::out|ios::app,0);
    8.     if(!myfile)
    9.     {
    10.         cout<<"文件写错误,文件属性可能为只读!"<<endl;
    11.         system("pause");
    12.         exit(1);
    13.     }
    14.     myfile<<"中国软件开发实验室"<<endl<<"网址:"<<"www.cndev-lab.com"<<endl;
    15.     myfile.close();
    16.     myfile.open("c:\\1.txt",ios::in,0);
    17.     if(!myfile)
    18.     {
    19.         cout<<"文件读错误,文件可能丢失!"<<endl;
    20.         system("pause");
    21.         exit(1);
    22.     }
    23.     char ch;
    24.     while(myfile.get(ch))
    25.     {
    26.         cout.put(ch);
    27.     }
    28.     myfile.close();
    29.     system("pause");
    30. }
      由于fstream类可以对文件同时进行读写操作,所以对它的对象进行初始话的时候一定要显式的指定mode和openprot参数。

      接下来我们来学习一下串流类的基础知识,什么叫串流类?

      我们先看看看C++是如何对C风格的字符串流进行控制的,C中的字符串其实也就是字符数组,字符数组内的数据在内存中的位置的排列是连续的,我们通常用 char str[size]或者char *str的方式声明创建C风格字符数组,为了能让字符数组作为设备并提供输入输出操作,C++引入了ostrstream、istrstream、 strstream这三个类,要使用他们创建对象就必须包含strstream.h头文件。

    • istrstream类用于执行C风格的串流的输入操作,也就是以字符串数组作为输入设备。
    • ostrstream类用于执行C风格的串流的输出操作,也就是一字符串数组作为输出设备。
    • strstream类同时可以支持C风格的串流的输入输出操作。

      istrstream类是从istream(输入流类)和strstreambase(字符串流基类)派生而来,ostrstream是从 ostream(输出流类)和strstreambase(字符串流基类)派生而来,strstream则是从iostream(输入输出流类)和和 strstreambase(字符串流基类)派生而来。

      他们的继承关系如下图所示:
    C++的iostream标准库介绍 - Elivans - Elivans的博客

      串流同样不是标准设备,不会有预先定义好的全局对象,所以不能直接操作,需要通过构造函数创建对象。

    类istrstream的构造函数原形如下:

      istrstream::istrstream(const char *str,int size);
      参数1表示字符串数组,而参数2表示数组大小,当size为0时,表示istrstream类对象直接连接到由str所指向的内存空间并以\0结尾的字符串。

      下面的示例代码就是利用istrstream类创建类对象,制定流输入设备为字符串数组,通过它向一个字符型对象输入数据。代码如下:

    1. #include <iostream>
    2. #include <strstream>
    3. using namespace std;
    4. int main()
    5. {
    6.     char *name = "www.cndev-lab.com";
    7.     int arraysize = strlen(name)+1;
    8.     istrstream is(name,arraysize);
    9.     char temp;
    10.     is>>temp;
    11.     cout<<temp;
    12.     system("pause");
    13. }
      类ostrstream用于执行串流的输出,它的构造函数如下所示:
      ostrstream::ostrstream(char *_Ptr,int streamsize,int Mode = ios::out);
      第一个参数是字符数组,第二个是说明数组的大小,第三个参数是指打开方式。

      我们来一个示例代码:

    1. #include <iostream>
    2. #include <strstream>
    3. using namespace std;
    4. int main()
    5. {
    6.     int arraysize=1;
    7.     char *pbuffer=new char[arraysize];
    8.     ostrstream ostr(pbuffer,arraysize,ios::out);
    9.     ostr<<arraysize<<ends;//使用ostrstream输出到流对象的时候,要用ends结束字符串
    10.     cout<<pbuffer;
    11.     delete[] pbuffer;
    12.     system("pause");
    13. }
      上面的代码中,我们创建一个c风格的串流输出对象ostr,我们将arraysize内的数据成功的以字符串的形式输出到了ostr对象所指向的pbuffer指针的堆空间中,pbuffer也正是我们要输出的字符串数组,在结尾要使用ends结束字符串,如果不这么做就有溢出的危险。
      stringstream::stringstream(string str);
      示例代码如下:
    1. #include <iostream>
    2. #include <sstream>
    3. #include <string>
    4. using namespace std;
    5. int main()
    6. {
    7.     stringstream ostr("ccc");
    8.     ostr.put('d');
    9.     ostr.put('e');
    10.     ostr<<"fg";
    11.     string gstr = ostr.str();
    12.     cout<<gstr<<endl;
    13.     char a;
    14.     ostr>>a;
    15.     cout<<a;
    16.     system("pause");
    17. }
      除此而外,stringstream类的对象我们还常用它进行string与各种内置类型数据之间的转换。示例代码如下:
    1. #include <iostream>
    2. #include <sstream>
    3. #include <string>
    4. using namespace std;
    5. int main()
    6. {
    7.     stringstream sstr; //--------int转string-----------
    8.     int a=100;
    9.     string str;
    10.     sstr<<a;
    11.     sstr>>str;
    12.     cout<<str<<endl; //--------string转char[]--------
    13.     sstr.clear();//如果你想通过使用同一stringstream对象实现多种类型的转换,请注意在每一次转换之后都必须调用clear()成员函数。
    14.     string name = "colinguan";
    15.     char cname[200];
    16.     sstr<<name;
    17.     sstr>>cname;
    18.     cout<<cname;
    19.     system("pause");
    20. }
      接下来我们来学习一下输入/输出的状态标志的相关知识.

    有两种方法可以获得输入/输出的状态信息。一种方法是通过调用rdstate()函数,它将返回当前状态的错误标记。例如,假如没有任何错误,则rdstate()会返回goodbit.下例示例,表示出了rdstate()的用法:

    1. #include <iostream>
    2. using namespace std;
    3. int main()
    4. {
    5.     int a;
    6.     cin>>a;
    7.     cout<<cin.rdstate()<<endl;
    8.     if(cin.rdstate() == ios::goodbit)
    9.     {
    10.         cout<<"输入数据的类型正确,无错误!"<<endl;
    11.     }
    12.     if(cin.rdstate() == ios_base::failbit)
    13.     {
    14.         cout<<"输入数据类型错误,非致命错误,可清除输入缓冲区挽回!"<<endl;
    15.     }
    16.     system("pause");
    17. }
      另一种方法则是使用下面任何一个函数来检测相应的输入/输出状态:
    bool bad(); bool eof(); bool fail(); bool good();

      下例示例,表示出了上面各成员函数的用法:

    1. #include <iostream>
    2. using namespace std;
    3. int main()
    4. {
    5.     int a;
    6.     cin>>a;
    7.     cout<<cin.rdstate()<<endl;
    8.     if(cin.good())
    9.     {
    10.         cout<<"输入数据的类型正确,无错误!"<<endl;
    11.     }
    12.     if(cin.fail())
    13.     {
    14.         cout<<"输入数据类型错误,非致命错误,可清除输入缓冲区挽回!"<<endl;
    15.     }
    16.     system("pause");
    17. }
      如果错误发生,那么流状态既被标记为错误,你必须清除这些错误状态,以使你的程序能正确适当地继续运行。要清除错误状态,需使用clear()函数。此函数带一个参数,它是你将要设为当前状态的标志值。,只要将ios::goodbit作为实参。

      示例代码如下:

    1. #include <iostream>
    2. using namespace std;
    3. int main()
    4. {
    5.     int a;
    6.     cin>>a;
    7.     cout<<cin.rdstate()<<endl;
    8.     cin.clear(ios::goodbit);
    9.     cout<<cin.rdstate()<<endl;
    10.     system("pause");
    11. }
    通常当我们发现输入有错又需要改正的时候,使用clear()更改标记为正确后,同时也需要使用get()成员函数清除输入缓冲区,以达到重复输入的目的。

      示例代码如下:

    1. #include <iostream>
    2. using namespace std;
    3. int main()
    4. {
    5.     int a;
    6.     while(1)
    7.     {
    8.         cin>>a;
    9.         if(!cin)//条件可改写为cin.fail()
    10.         {
    11.             cout<<"输入有错!请重新输入"<<endl;
    12.             cin.clear();
    13.             cin.get();
    14.         }
    15.         else
    16.         {
    17.             cout<<a;
    18.             break;
    19.         }
    20.     }
    21.     system("pause");
    22. }
      最后再给出一个对文件流错误标记处理的例子,巩固学习,代码如下:

    1. #include <iostream>
    2. #include <fstream>
    3. using namespace std;
    4. int main()
    5. {
    6.     ifstream myfile("c:\\1.txt",ios_base::in,0);
    7.     if(myfile.fail())
    8.     {
    9.         cout<<"文件读取失败或指定文件不存在!"<<endl;
    10.     }
    11.     else
    12.     {
    13.         char ch;
    14.         while(myfile.get(ch))
    15.         {
    16.             cout<<ch;
    17.         }
    18.         if(myfile.eof())
    19.         {
    20.             cout<<"文件内容已经全部读完"<<endl;
    21.         }
    22.         while(myfile.get(ch))
    23.         {
    24.             cout<<ch;
    25.         }
    26.     }
    27.     system("pause");
    28. }

      未完待续……


    阅读(1347) | 评论(0) | 转发(1) |
    给主人留下些什么吧!~~