// scanf() method (limited)
char name[50];
scanf("%s", name); // Stops at first space
// fgets() method (recommended)
fgets(name, sizeof(name), stdin);
2. Dynamic Memory Allocation
char *dynamicInput(void) {
char *buffer = NULL;
size_t bufferSize = 0;
// Use getline() for flexible input
ssize_t characters = getline(&buffer, &bufferSize, stdin);
if (characters == -1) {
free(buffer);
return NULL;
}
// Remove trailing newline
buffer[strcspn(buffer, "\n")] = '\0';
return buffer;
}
graph TD
A[User Input] --> B{Input Method}
B --> |Static Array| C[Fixed Memory]
B --> |Dynamic Allocation| D[Flexible Memory]
C --> E[Process String]
D --> E
E --> F[Validate Input]
Technique |
Pros |
Cons |
Best For |
scanf() |
Simple |
No spaces |
Short inputs |
fgets() |
Handles spaces |
Includes newline |
Most scenarios |
getline() |
Dynamic allocation |
Requires manual free |
Complex inputs |
Error Handling Strategies
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* safeStringInput(int maxLength) {
char *input = malloc(maxLength * sizeof(char));
if (input == NULL) {
fprintf(stderr, "Memory allocation failed\n");
return NULL;
}
if (fgets(input, maxLength, stdin) == NULL) {
free(input);
return NULL;
}
// Remove newline
input[strcspn(input, "\n")] = '\0';
return input;
}
Tokenization Example
#include <stdio.h>
#include <string.h>
void parseInput(char *input) {
char *token = strtok(input, " ");
while (token != NULL) {
printf("Token: %s\n", token);
token = strtok(NULL, " ");
}
}
int main() {
char input[100];
fgets(input, sizeof(input), stdin);
input[strcspn(input, "\n")] = '\0';
parseInput(input);
return 0;
}
Best Practices
- Always validate input
- Use appropriate memory management
- Handle potential errors
- Choose method based on specific requirements
graph LR
A[Input Method] --> B{Performance}
B --> |Fast| C[scanf()]
B --> |Flexible| D[fgets()]
B --> |Dynamic| E[getline()]
LabEx recommends mastering these techniques for robust string input handling in C programming.