Skip to content

Instantly share code, notes, and snippets.

@zxytim
Created December 21, 2012 06:45
Show Gist options
  • Save zxytim/4351091 to your computer and use it in GitHub Desktop.
Save zxytim/4351091 to your computer and use it in GitHub Desktop.
A template for fast read of integer and string for c++.
/*
* $File: fast-read.cc
* $Date: Fri Dec 21 14:44:05 2012 +0800
* $Author: Xinyu Zhou <zxytim[at]gmail[dot]com>
*
* A template for fast read of integer and string.
*
* This implementation is in MACRO format because it
* yields a slightly faster code that that of using
* function calls.
*
* This version of code uses a fixed size buffer to store
* inputs by *fread*, and analyze the string manually to convert it
* to int or string. Also, update the buffer when it is exhausted.
*
* sample usage:
* READ_INT(num);
* READ_STR(str); // str is a char*, which no boundary checking
*/
/* {{{ fast read*/
#include <cstdio>
#include <cctype>
FILE *fast_read_fin = stdin;
const int N_BUF_MAX = 10000;
char fast_read_buffer[N_BUF_MAX];
char *fast_read_ptr = fast_read_buffer + N_BUF_MAX,
*fast_read_buf_end = fast_read_buffer + N_BUF_MAX;
#define PTR_NEXT() \
do { \
if (fast_read_ptr != fast_read_buf_end) \
break; \
fast_read_ptr = fast_read_buffer; \
fread(fast_read_buffer, N_BUF_MAX, 1, fast_read_fin); \
} while (0)
#define READ_INT(__num__) \
do { \
int ret = 0, sign = 1; \
for (; ;) \
{ \
PTR_NEXT(); \
if (isdigit(*fast_read_ptr) || (*fast_read_ptr) == '-') \
break; \
fast_read_ptr ++; \
} \
if ((*fast_read_ptr) == '-') \
{ \
sign = -1; \
fast_read_ptr ++; \
} \
for (; ;) \
{ \
PTR_NEXT(); \
if (!isdigit(*fast_read_ptr)) \
break; \
ret = ret * 10 + (*(fast_read_ptr ++)) - '0'; \
} \
(__num__) = ret * sign; \
} while (0)
#define READ_STR(__str__) \
({ \
char *start = (__str__), \
*ret = start; \
do { \
for (; ;) \
{ \
PTR_NEXT(); \
if (!isspace(*fast_read_ptr)) \
break; \
fast_read_ptr ++; \
} \
for (; ;) \
{ \
PTR_NEXT(); \
if (isspace(*fast_read_ptr)) \
break; \
*(ret ++) = *(fast_read_ptr ++); \
} \
(*ret) = 0; \
} while (0); \
ret - start; \
})
/* }}}*/
int main()
{
int a, b;
READ_INT(a);
READ_INT(b);
printf("%d\n", a + b);
return 0;
}
/**
* vim: syntax=cpp11 foldmethod=marker
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment