【c++编程思想】输入输出流

  • 插入符与提取符
 
自己定义的插入符和提取符, 就可以重载相关运算符以完成相关的操作。
1.第一个参数定义成流(输入为istream,输出为ostream)的非const引用。
2.执行向流中插入/提取的操作,通过处理对象的组成元素
3.返回流的引用
输入输出流应该是非常量,通过返回流,可以将这些流操作连接成单一语句。
 
#include<iostream>
using namespace std;

class date{
    public:
    int year;
    int month;
    int day;
    date(int n_year, int n_month, int n_day)
    {
        year = n_year;
        month = n_month;
        day = n_day;
    }
};

ostream& operator<<(ostream&os, const date& d)
{
    os<<d.year<<"-"<<d.month<<"-"<<d.day<<"my own function"<<endl;
    return os;
}

int main()
{
    date d(2012, 10, 2);
    cout<<d;
}

 

 
这个函数不能称为date类的成员函数,因为<<左边的操作数必须是输出流
istream& operator>>(istream& is, date& d)
{
    char dash;
    is>>d.year;
    is>>dash;
    if(dash != '-')
        is.setstate(ios::failbit);
    is>>d.month;
    is>>dash;
    if(dash != '-')
        is.setstate(ios::failbit);
    is>>d.day;
    return is;
}

 

使用输入流需要注意输入数据错误,通过设置流的失败标志位,就可以表明产生了流错误。
一旦失败标志位被设置,则在流恢复到有效状态之前,此外所有的流操作都会被忽略。
 
 
 
 
  • 按行输入
有三种方式可以实现按行输入
成员函数get
成员函数getline
定义在头文件中的全局函数getline
前两个函数有三个参数:指向字符缓冲区的指针, 缓冲区的大小, 结束字符
 
1.    cin.get(ch) || ch=cin.get()
可以用来接收单个字符
 
 2.    cin.get(字符数组名,接收字符数)
可以用来接收一行字符, 包括空格。
 
3.    cin.getline(字符数组名,接收字符数,第三个参数默认为'\0') 
接收一个字符串,可以带空格
 
4.    getline(cin, str)
全局函数, 可以接收空格
 
 
 
  • 文件输入输出流
int main()
{
    const int sz = 100;
    char buf[sz];
    ifstream in("D:\\test.txt");
    ofstream out("D:\\outtest.txt");
    
    while(in.get(buf, sz))  //读入字符到缓冲区,但是跳过输入流中的结束字符
    {
        in.get();  //丢掉结束字符  或者使用ignore
        cout<<buf<<endl;   //输出到标准输出中
        out<<buf<<endl;  //输出到文件中
    }
}

 

 
  • 输入输出缓冲流
重要的是产生和消耗数据的输入输出流部分进行通信。抽象成一个类,称为streambuf。每个输入输出流对象包含一个指向streambuf的指针。它有一些成员函数,可以对buf进行操作。
rdbuf返回一个指向streambuf的指针,通过这个指针可以对streambuf进行存取,这样就可以调用任何函数。
更重要的是可以将其和另一个输入输出流对象用<<连接,这样把右边的字符都输出到左侧的对象中去。
ifstream in("D:\\test.txt");
ofstream out("D:\\outtest.txt");
cout<<in.rdbuf()<<endl;
 
 
 
  • 字符串输入输出流
如果需要创建一个字符串流,并从这个流读取字符,可以创建istringstream,如果写就用ostringstream都包括在sstream
 
int main()
{
    string s;
    cin>>s;
    istringstream os(s);
    date d;
    os>>d;
    cout<<d;
}

 

 
输出字符串流也同理
int main()
{
    string s;
    cin>>s;
    istringstream os(s);
    ostringstream ostr;
    date d;
    os>>d;
    ostr<<d;
    cout<<ostr.str()<<endl;
}

 

 
posted @ 2012-09-12 19:08  w0w0  阅读(236)  评论(0编辑  收藏  举报