欢迎来到贱贱的博客

扩大
缩小

c++中IO输入输出流总结<二>

1 文件的打开和关闭

1.1 定义流对象

  ifsteam iflie;//文件输入流对象

  ifsteam iflie;//文件输出流对象

  fsteam iflie;//文件输入输出流对象

1.2 打开文件

  void open(const unsigned char* filename,int mode,int accessfilebuf:opnprot)

    mode为打开的方式,相关标记如下图所示(ios中)

    

  注意:

    (1)通常打开方式用|组合起来

       ios::in|ios::out  //读写方式打开文件

       ios::out|ios::binary //二进制写方式打开文件

    (2)iftream:默认ios::in

     ofstream:默认ios::out|ios::trunc

     fstream:默认ios::in|ios::out|ios::app

2 状态函数

  eof():读文件到达末尾 true

  bad():读文件出错返回true 当我打开一个不可以写但是进行写入的时候

  fail:当需要输入整形的时候我们输入了字母

  good:如果上面任何一个函数都是true的话 返回false

  clear():

#include <iostream>
#include <stdlib.h>
using namespace std;

int main()
{
    int integerV;
    cout << "before a bad input operation:"
        << "\n cin.eof():" << cin.eof()
        << "\n cin.fail():" << cin.fail()
        << "\ncin.bad():" << cin.bad()
        << "\ncin.good()" << cin.good() << endl;
    cin >> integerV;//control +D/Z
    cout << "after a bad input operation:"
        << "\n cin.eof():" << cin.eof()
        << "\n cin.fail():" << cin.fail()
        << "\ncin.bad():" << cin.bad()
        << "\ncin.good()" << cin.good() << endl;
    system("pause");
    return 1;

}

3 (cin)和(!cin)的分析

  不管是while(cin)还是if(cin)都是合法的为什么?自定义一个类,然后定义这个类的对象,使用if语句判断它是不合法的。说明流对象有莫中转换函数 可以将一个流对象转换成判断语句可以识别的类型

operator void*() const函数在while(cin)或者if(cin)隐式转换位void*类型
bool operator!() const;函数在while(!cin)或者式if(!cin)被调用 将流对象转换成bool对象
while(cin)--->while(!cin.fail)
while(!cin)---->while(cin.fail)

 1 class A
 2 {
 3 public:
 4     A(){}
 5     ~A(){}
 6     operator void*() const
 7     {
 8         cout << "cast to void*";
 9         return (void*)this;
10     }
11     bool operator!() const
12     {
13         cout << "cast to bool";
14         return true;
15     }
16 };
17 
18 int main()
19 {
20     A a;
21     if (a)cout << "first" << endl;
22     if (!a)cout << "second" << endl;
23     system("pause");
24     return 1;
25 }

4 文件读写操作

 

posted on 2017-08-05 12:05  L的存在  阅读(281)  评论(0编辑  收藏  举报

导航