C - Reading Newline Characters into a String

Introduction

You could implement the input process by using the fgets() function, which stores the newline character in a string.

The fgets() function requires three arguments:

  • the address of the input array
  • the maximum number of characters to be read
  • the source of the input, which for the keyboard will be stdin.

Demo

#define __STDC_WANT_LIB_EXT1__ 1           // Make optional versions of functions available
#include <stdio.h>
#include <string.h>
#include <stdbool.h>

int main(void)
{
  char delimiters[] = " \n\".,;:!?)(";     // Prose delimiters
  char buf[100];                           // Buffer for a line of keyboard input
  char str[1000];                          // Stores the prose to be tokenized
  char* ptr = NULL;                        // Pointer used by strtok_s()
  str[0] = '\0';                           // Set 1st character to null
  size_t str_len = sizeof(str);
  size_t buf_len = sizeof(buf);

  printf("Enter some prose that is less than %zd characters.\n"
    "Terminate input by entering an empty line:\n", str_len);

  // Read multiple lines of prose from the keyboard
  while (true)
  {// w  w w. ja  va 2  s  . c  o m
    if (!fgets(buf, buf_len, stdin))        // Read a line of input
    {
      printf("Error reading string.\n");
      return 1;
    }
    if (buf[0] == '\n')                     // An empty line ends input
      break;
    if (strcat_s(str, str_len, buf))        // Concatenate the line with str
    {
      printf("Maximum permitted input length exceeded.");
      return 1;
    }
  }

  // Rest of the code as for Program 6.7...
  return 0;
}

Result

Related Example