Fast Input Output In CPP /C

Fast Input/Output in C

Have You ever get Time limit Exceeded due to the slow input/output in C.

Its better to  use the following function while taking input from the console .

#define gc getchar_unlocked
int read_int() {
  char c = gc();
  while(c<'0' || c>'9') c = gc();
  int ret = 0;
  while(c>='0' && c<='9') {
    ret = 10 * ret + c - 48;
    c = gc();
  }
  return ret;
}

On windows while testing , you can change #define gc getchar_unlocked to #define gc getchar and change back while submitting.

Now to get the string input use the following function-

inline void fastRead_string(char *str)
{
   register char c = 0;
   register int i = 0;

   while (c < 33)
       c = getchar_unlocked();
   while (c != '\n') {
       str[i] = c;
       c = getchar_unlocked();
       i = i + 1;
   }
   str[i] = '';
}

Using these functions:

int main()
{
  int n;
  char s[100];
  read_int(n);
    printf("%d\n", n);

  fastRead_string(s);
    printf("%s\n", s);
  return 0;
}

Fast Input/Output in CPP

With the starting of the main function in cpp you should use the following line to get fast input.

ios::sync_with_stdio(false);