Reading a String Using fgets in C programming

Reading a String Using <code>fgets</code> in C

Reading a String Using fgets in C

The fgets function in C is used to read a string of characters from a file or standard input, such as the keyboard. It is particularly useful for handling user input because it can read an entire line of text, including spaces, until a newline character is encountered or the specified limit is reached.

Syntax

The syntax for fgets is as follows:

char *fgets(char *str, int n, FILE *stream);

Where:

  • str is a pointer to a character array where the input string will be stored.
  • n is the maximum number of characters to read, including the null terminator.
  • stream is the file pointer from which the input will be read. Use stdin for standard input.

Example Code

#include <stdio.h>

int main() {
    char buffer[100]; // Buffer to store the input

    printf("Enter a string: ");
    fgets(buffer, sizeof(buffer), stdin);

    printf("You entered: %s", buffer);

    return 0;
}

In this example:

  • char buffer[100]; declares a character array of size 100 to store the input string.
  • printf("Enter a string: "); prompts the user to enter a string.
  • fgets(buffer, sizeof(buffer), stdin); reads up to 99 characters from standard input and stores them in buffer. It automatically appends a null terminator.
  • printf("You entered: %s", buffer); prints the string stored in buffer.

Key Points

  • Buffer Size: Ensure the buffer size is large enough to accommodate the input string and the null terminator.
  • Newline Character: fgets includes the newline character in the buffer if it fits within the specified limit.
  • Error Handling: Always check for potential errors, such as reaching the end of file or an empty input.
Note: fgets is safer than gets because it prevents buffer overflow by specifying the maximum number of characters to read.

Comments

Popular Posts