---
title: Optimized Input and Output in C++
tags:
  - C/C++
id: "2583"
categories:
  - - Coding
    - Programming Language
date: 2018-03-14 20:35:32
---

## Background

C++标准库`<iostream>`中的`cin, cout`相比`<cstdio>`中的`scanf, printf`要方便许多，但速度也较为缓慢。在输入输出的数据类型不是很特殊时，可以使用以下代码来代替`cin, cout`（要包含`<cctype>, <cstdio>`，不要包含`<iostream>`）。

## Code

```cpp
class InputStream {
private:
  static int const BUFFER_SIZE = 10000000;
  char *buffer;

public:
  InputStream() {
    buffer = new char[BUFFER_SIZE]();
    fread(buffer, sizeof(char), BUFFER_SIZE, stdin);
  }
  InputStream &operator>>(int &n) {
    for (; *buffer < '0' || *buffer > '9'; ++buffer)
      ;
    for (n = 0; *buffer >= '0' && *buffer <= '9';
         (n *= 10) += *(buffer++) - '0')
      ;
    return *this;
  }
  InputStream &operator>>(char &c) {
    for (; !isprint(*buffer) || *buffer == ' '; ++buffer)
      ;
    c = *(buffer++);
    return *this;
  }
  InputStream &operator>>(char *s) {
    char *t = s;
    for (; !isprint(*buffer) || *buffer == ' '; ++buffer)
      ;
    for (; isprint(*buffer) && *buffer != ' '; *(t++) = *(buffer++))
      ;
    *t = '\0';
    return *this;
  }
} cin;

class OutputStream {
private:
  static int const BUFFER_SIZE = 10000000;
  char *buffer, *cur;

public:
  OutputStream() { buffer = cur = new char[BUFFER_SIZE](); }
  ~OutputStream() { fwrite(buffer, sizeof(char), cur - buffer, stdout); }
  OutputStream &operator<<(int const &n) {
    for (sprintf(cur, "%d", n); *cur; ++cur)
      ;
    return *this;
  }
  OutputStream &operator<<(char const &c) {
    *(cur++) = c;
    return *this;
  }
  OutputStream &operator<<(char *s) {
    for (char *t = s; *t; *(cur++) = *(t++))
      ;
    return *this;
  }
} cout;

static char const endl = '\n';
```
