C++标准IO

cin(标准输入),cout(标准输出),cerr(不带缓存的标准错误输出),clog(带缓存的标准错误输出)。

文件读写操作,分别为:ifstream(读文件),ofstream(写文件),fstream(读写文件)

字符串作为输入输出流进行处理,分别为:istringstream(字符串输入流),ostringstream(字符串输出流),stringstream(字符串输入输出流)。

每种流对应一个缓冲区类(filebuf,stringbuf)。

#include <iostream>
using namespace std;

int main(void){
    cout.put('A');
    cout << endl;
    /*向流中插入一个字符串*/
    char *str = "Hello World !";
    cout.write(str, strlen(str));
    cout << endl;
    cout.write(str + 6, strlen(str));
    cout << endl;
    /*向流中提取字符,
    getline()遇输入流中的停止符,并提取停止符,把‘\0’加至最后*/
    char str2[20];
    cout << "input str:";
    cin.getline(str2, sizeof(str2));
    cout << str2 << endl;
    /*get()遇输入流中的停止符,但不提取停止符*/
    char str1[5];
    cout << "input str:";
    cin.get(str1, sizeof(str1));
    cout << str1 << endl;
    return 0;
}

文件读写处理:

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

void main(){
    /*将信息写入test.txt*/
    ofstream outfile("d:\\test.txt", ios::out); //以写方式打开文件
    if (!outfile)
    {
        cerr << "打开文件错误" << endl;           //标准错误输出
        abort();                               //终止进程,使所有的流被关闭和冲洗
    }
    else{
        outfile << "1.Hangzhou" << endl;  
        outfile << "\n" << endl;
        outfile << "2.Shanghai" << endl;
    }
    outfile.close();
    /*读test.txt信息*/
    char s[20];
    ifstream infile("d:\\test.txt", ios::in);  //以读方式打开文件
    if (!infile)
        cerr << "打开文件错误" << endl;          //标准错误输出
    else{
        infile.getline(s, 20);                 //提取一行字符
        cout << s << endl;
        while (!infile.eof())                  //文件不结束执行
        {
            infile.getline(s, 20);     
            cout << s << endl;
        }
    }
    infile.close();   
}

文件复制:

    ifstream infile("d:\\test.txt", ios::in);            
    if (!infile)
    {
        cerr << "文件test.txt打开错误" << endl;
        abort();                
    }
    ofstream outfile("d:\\test1.txt", ios::out);
    if (!outfile)
    {
        cerr << "文件test1.txt打开错误" << endl;
        abort();                
    }
    char ch;
    while (infile.get(ch))            //文件流中逐个读出字符,直到文件结束
        outfile.put(ch);
    infile.close();
    outfile.close();    

 

posted @ 2015-02-04 23:30  ht-beyond  阅读(289)  评论(0编辑  收藏  举报