快速读入输出模板

fread快速读入+fwrite快速输出大法好。

实测比普通读入优化快一倍,输出不知道高到哪里去了。

/*
 * 快速读入输出模板     Au: Hatsune Miku
 * 用法:
 *       1. 在打开文件后立即调用init()函数初始化缓冲区。
 *       2. 读入时请使用 read()读入,可以读入字符串(仅限字母)与数字。
 *       3. 输出时请使用 print()输出到缓冲区,可以输出字符串、数字与字符。
 *       4. 在关闭文件前使用 flush()刷新缓存区(真正输出到文件中)。
 * 函数返回值:
 *            1. 所有输入操作均有返回值,返回真表示读入成功,变量已被修改,返回假表示读不到指定类型的数据,变量被清零;
 *            2. 所有输出操作均无返回值,缓冲区自动刷新。
 *            3. 初始化函数无返回值,如果超出缓冲区会RE。
 * 玩得愉快!
*/
#include<cstdio>
#include<cctype>
#include<cstdlib>
#include<assert.h>
using namespace std;

const int InputBufferSize = 67108864;//输入缓冲区大小
const int OutputBufferSize = 67108864;//输出缓冲区大小 

namespace input
{
    char buffer[InputBufferSize],*s,*eof;
    inline void init()
    {
        assert(stdin!=NULL);
        s=buffer;
        eof=s+fread(buffer,1,InputBufferSize,stdin);
    }
    inline bool read(int &x)
    {
        x=0;
        int flag=1;
        while(!isdigit(*s)&&*s!='-')s++;
        if(eof<=s)return false;
        if(*s=='-')flag=-1,s++;
        while(isdigit(*s))x=x*10+*s++-'0';
        x*=flag;
        return true;
    }
    inline bool read(char* str)
    {
        *str=0;
        while(isspace(*s))s++;
        if(eof<s)return false;
        while(!isspace(*s))*str=0,*str=*s,str++,s++;
        *str=0;
        return true;
    }
}

namespace output
{
    char buffer[OutputBufferSize];
    char *s=buffer;
    inline void flush()
    {
        assert(stdout!=NULL);
        fwrite(buffer,1,s-buffer,stdout);
        s=buffer;
        fflush(stdout);
    }
    inline void print(const char ch)
    {
        if(s-buffer>OutputBufferSize-2)flush();
        *s++=ch;
    }
    inline void print(char* str)
    {
        while(*str!=0)print(char(*str++));
    }
    inline void print(int x)
    {
        char buf[25]= {0},*p=buf;
        if(x<0)print('-'),x=-x;
        if(x==0)print('0');
        while(x)*(++p)=x%10,x/=10;
        while(p!=buf)print(char(*(p--)+'0'));
    }
}

using namespace input;
using namespace output;

int num;

int main()
{
    freopen("data.in","rb",stdin);//请根据题目修改文件名
    freopen("data2.out","wb",stdout);//请根据题目修改文件名
    init();
    /*
       ...
       此处应有代码。
       ...
       下面的代码示例读入一个数列,然后输出这个数列。
       ``````````````````````````````````````
       ` int a;                             `
       ` while(read(a))print(a),print(' '); `
       ``````````````````````````````````````
    */
    while(read(num))print(num),print(' ');
    flush();
    return 0;
}

  

posted @ 2018-03-24 16:55  baka  阅读(2539)  评论(0编辑  收藏  举报