C++每日一练(I/O)

来源:互联网 发布:苹方字体 mac版下载 编辑:程序博客网 时间:2024/05/16 16:58

一、今日课题

I/O

二、实战演练

大多数计算机语言的输入输出的实现都是以语言本身为基础的,但是C/C++没有这样做。C语言最初把I/O留给了编译器实现人员。这样做的一个原因是可以提供足够的自由度,使之最适合目标机器的硬件条件。但是大多数实现人员都将I/O建立在了Unix库函数中,之后C才将该库引入了C标准中,被C++继承了下来。

但是C++也有自己的I/O解决方案,将其定义于iostream和fstream中。这两个库不是语言的组成部分,只是定义了一些类而已。

C++把输入和输出看作字节流。对于面向文本的程序,一个字节代表一个字符。流充当了源于目标之间的桥梁,因此对流的管理包含两个方面:从哪里来,到哪里去。其中,缓冲区作为临时存储空间,可以提高流处理的速度。

C++中专门定义了一些类来管理流和缓冲区:

C++98定义了一些模板类,用以支持char和wchar_t类型;

C++ 11添加了char16_t和char32_t类型(实则就是一些typedef来模拟不同的类型)。

这里写图片描述

1)有何用?

iostream库自动定义了一些标准对象:

  • cout, ostream类的一个对象,可以将数据显示在标准输出设备上.

  • cerr, ostream类的另一个对象,它无缓冲地向标准错误输出设备输出数据.

  • clog, 类似cerr,但是它使用缓冲输出.

  • cin, istream类的一个对象,它用于从标准输入设备读取数据.

fstream库允许编程人员利用ifstream和ofstream类进行文件输入和输出.

2)怎么用?

///C++ I / O操作——简单文件加密#include <iostream>#include<fstream>#include <string>using namespace std;int main(){    string str;    char buffer[256];    int psw, a;    cout << "encode or decode ? if encode, please input 1 else decode input 2 :" << endl;   // encode or decode ?      cin >> a;                                                         cout << "please input the psw:" << endl;                            // input psw      cin >> psw;    if (a == 2)        psw = 0 - psw;    cout << "please input the filename of source...." << endl;           // input source file         cin >> str;    fstream outfile(str.c_str(), ios::in);    cout << "please input the filename of destinity...." << endl;       // input destiny file      cin >> str;    ofstream outtxt(str.c_str(), ios::ate | ios::out);    while (!outfile.eof())                                         // process       {        cout << "222" << endl;        outfile.getline(buffer, 256, '\n');        cout << buffer << endl;        for (int i = 0; i < strlen(buffer); i++)                   //algorithm of encode or decode              buffer[i] = buffer[i] + psw;        outtxt << buffer << endl;    }    outfile.clear();    outfile.close();    return 0;}

3)Access & Operations

这里写图片描述


三、C++树

这里写图片描述


10/14/2016 3:49:44 PM

0 0