C Program to take string as an input

Category: C Program

Learn how to take string input in C using various methods including scanf, gets, fgets, and getchar. Discover the advantages and disadvantages of each method to write secure and efficient C code.

Handling strings is a fundamental aspect of programming, and in C, there are several methods to take string input. Each method has its own advantages and disadvantages. In this article, we'll explore these methods and provide sample code to demonstrate their usage.

Methods to Take String Input in C

  1. Using scanf
  2. Using gets
  3. Using fgets
  4. Using getchar in a loop

1. Using scanf

scanf is a standard function in C used to read formatted input from the standard input (stdin).

#include <stdio.h>

int main() {
    char str[100];
    printf("Enter a string: ");
    scanf("%99s", str); // Limit input to avoid buffer overflow
    printf("You entered: %s", str);
    return 0;
}

We can also use this scanf("%[^\n]c", str); to stop taking input on a new line character.

Advantages:

  • Simple and easy to use for basic input.
  • Automatically handles input until the first whitespace character.

Disadvantages:

  • Stops reading at the first whitespace (space, tab, newline), making it unsuitable for multi-word strings.
  • Risk of buffer overflow if input exceeds the allocated size.

2. Using gets

gets reads a line from stdin into the buffer until a terminating newline or EOF.

#include <stdio.h>

int main() {
    char str[100];
    printf("Enter a string: ");
    gets(str); // Deprecated and unsafe
    printf("You entered: %s", str);
    return 0;
}

Advantages:

  • Reads the entire line, including spaces, making it suitable for multi-word strings.

Disadvantages:

  • Unsafe and deprecated due to the risk of buffer overflow.
  • No way to specify the maximum length of input.

3. Using fgets

fgets reads a specified number of characters from stdin, ensuring safe input handling.

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

int main() {
    char str[100];
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);
    // Remove trailing newline character, if present
    str[strcspn(str, "\n")] = '\0';
    printf("You entered: %s", str);
    return 0;
}

Advantages:

  • It is safer than gets as it prevents buffer overflow by limiting the number of characters read.
  • Suitable for multi-word strings.

Disadvantages:

  • Includes the newline character in the input, requiring additional handling to remove it.

4. Using getchar in a Loop

getchar reads one character at a time from stdin. Using it in a loop allows for custom handling of input.

#include <stdio.h>

int main() {
    char str[100];
    int i = 0;
    char ch;

    printf("Enter a string: ");
    while ((ch = getchar()) != '\n' && ch != EOF && i < 99) {
        str[i++] = ch;
    }
    str[i] = '\0';

    printf("You entered: %s\n", str);
    return 0;
}

Advantages:

  • Full control over input handling.
  • Can handle multi-word strings and custom termination conditions.

Disadvantages:

  • More complex to implement.
  • Requires manual handling of input size to avoid buffer overflow.

Conclusion

Each method of taking string input in C has its strengths and weaknesses. For simple, single-word input, scanf can be quite effective. However, for multi-word strings, fgets provides a safer and more robust option compared to the deprecated gets. The getchar in a loop method offers the most control but at the cost of complexity.

Summary of Methods:

  • scanf: Easy to use, not suitable for multi-word input.
  • gets: Simple and handles multi-word input, but deprecated and unsafe.
  • fgets: Safe and ideal for multi-word input, needs newline handling.
  • getchar in a loop: Maximum control and flexibility, more complex.

Choosing the right method depends on the specific requirements of your application, with safety and simplicity often guiding the decision.


Recommended Posts