Function Prototype
cchar *fgets(char *str, int n, FILE *stream);
- str is a pointer to an array that stores the read string.
- n is the maximum number of characters to read, including the null character ('\0').
- stream is the input stream; for reading from standard input, it should be stdin.
Usage Example
Below is a simple example using fgets() to read user input from stdin. In this example, we read a line of text from the user and echo it back.
c#include <stdio.h> int main() { char input[100]; // Declare a character array capable of storing up to 99 characters plus one null character printf("Please enter some text: "); if (fgets(input, sizeof(input), stdin)) { // Output the read data printf("You entered: %s", input); } else { // If read fails, output error message printf("Read error.\n"); } return 0; }
Notes
- Buffer Size: In the above example, we define a character array of size 100. This means we can read up to 99 characters of input, with the 100th position reserved for the terminating null character ('\0').
- Handling Newline Characters: fgets() reads the newline character ('\n') into the string as well. If you do not want the newline character to appear in the output, you must manually remove or replace it in the string.
- Error Handling: By checking the return value of fgets(), we can determine if the read was successful. If fgets() fails due to an error or end-of-file, it returns NULL.
Summary
Using fgets() to read from stdin provides a safe and flexible approach for handling user input. It prevents buffer overflow and can handle inputs of varying lengths. With appropriate error checking and input processing, the program becomes more robust and user-friendly.
2024年6月29日 12:07 回复