C - String Input Functions
In C, there are several standard library functions that you can use to read strings from the user or from input sources like files. These functions are commonly used for reading and processing textual data. Here are some of the commonly used string input functions in C:
1. scanf
:
scanf
is a versatile input function that can be used to read strings from the user. You can use the %s
format specifier to read a string until whitespace (space, tab, newline) is encountered.
char name[50];
printf("Enter your name: ");
scanf("%s", name);
2. gets
(Avoid using it):
gets
reads a line of text from the standard input (usually the keyboard) and stores it in a character array. It's considered unsafe to use because it doesn't specify the buffer size, which can lead to buffer overflows.
char sentence[100];
printf("Enter a sentence: ");
gets(sentence); // Unsafe, not recommended
3. fgets
:
fgets
is a safer alternative to gets
for reading lines of text. It reads a line of text from a specified input stream (e.g., stdin
for keyboard input) and stores it in a character array. It allows you to specify the maximum number of characters to read to avoid buffer overflows.
char sentence[100];
printf("Enter a sentence: ");
fgets(sentence, sizeof(sentence), stdin); // Recommended for reading lines of text
4. gets_s
and fgets_s
(C11 and later):
These are safer versions of gets
and fgets
introduced in C11 to address security concerns related to buffer overflows. They take an additional argument specifying the buffer size to prevent buffer overflows.
char sentence[100];
printf("Enter a sentence: ");
gets_s(sentence, sizeof(sentence));
5. getline
(Non-standard, POSIX):
getline
is a function available on POSIX systems (Unix/Linux) that reads an entire line from a file stream and allocates memory as needed to store the line. It is useful when reading lines of text from files with variable-length lines.
char *line = NULL;
size_t len = 0;
ssize_t read;
read = getline(&line, &len, stdin);
if (read != -1) {
// Process the line
}
free(line); // Free allocated memory
Remember to handle input validation and potential errors when using these functions to ensure robust and safe string input in your C programs. The choice of which function to use depends on your specific requirements and portability considerations.