FGETS()

reads a full line of input character by character (including spaces) from the keyboard and stores them into a string (character array). It reads until it reaches a newline character, the end of the file, or a specified number of characters. this function automatically adds a null terminator '\0' at the end of the str

// Read a full line of input from the user, including spaces

// It automatically adds '\0' at the end of the str

SYNTAX

fgets(str, size, stdin);

 * fgets() reads up to sizeof(str) - 1 characters or until a newline is found
#include <stdio.h>
#include <string.h>

int main() {
    char str[100];  // String to store input
    int buffer = sizeof(str) - 1;      //-1 accounts for the null terminator

    // Read a line of text from the user
    // sizeof(str) gives the total size of the 'str' array to prevent buffer overflow
    fgets(str, buffer, stdin);

    // Display the entered string
    printf("You entered: %s\n", str);

    return 0;
}

 * stdin represents the input method

#include <stdio.h>
#include <string.h>

int main() 
{
  // Declare and initialize the source string
  char source[100];
    
  // Declare a destination string with enough space
  char destination[100];
    
  //copies whatever user input
  fgets(source, sizeof(source) -1 , stdin);

  int n;
  scanf("%d", &n);
  if (n > (strlen(source))){
    n = strlen(source);
  }
  
  strncpy(destination, source, n);
    
  //Ensure that the copied string is null-terminated properly.
  destination[n] = '\0';
   
  printf("Copied portion: %s\n", destination);
    
  return 0;
}

 * this sample showcases the use of fgets instead of the scanf

Last updated