Read a Line of Text from the User
Obtaining user input can be done in many surprisingly different ways. This code is somewhere in the middle: safer than gets(text) or scanf("%s", text), but not bulletproof. It is meant to be a simple but relatively safe demonstration.
The function mygetline reads user input from the stdin into a string using fgets. Then it attempts to remove a trailing newline that fgets may leave in the string. It returns a pointer to the destination string.
Code:#include <stdio.h> #include <string.h> char *mygetline(char *line, int size) { if ( fgets(line, size, stdin) ) { char *newline = strchr(line, '\n'); /* check for trailing '\n' */ if ( newline ) { *newline = '\0'; /* overwrite the '\n' with a terminating null */ } } return line; } int main(void) { char text[20] = ""; fputs("prompt: ", stdout); fflush(stdout); printf("text = \"%s\"\n", mygetline(text, sizeof text)); return 0; } /* my input/output prompt: hello world text = "hello world" */
Read a Line of Text from the User, Discard Excess Characters
If the user tries to put 80 characters in a 20-character buffer, you may have issues. This snippet shows one way to cap the input and discard excess input.
Code:#include <stdio.h> char *mygettext(char *text, size_t size) { size_t i = 0; for ( ;; ) { int ch = fgetc(stdin); if ( ch == '\n' || ch == EOF ) { break; } if ( i < size - 1 ) { text[i++] = ch; } } text[i] = '\0'; return text; } int main(void) { int i; for ( i = 0; i < 3; ++i ) { char text[20]; fputs("prompt: ", stdout); fflush(stdout); printf("text = \"%s\"\n", mygettext(text, sizeof text)); } return 0; } /* my input/output prompt: 1234567890123456789012345 text = "1234567890123456789" prompt: hello world text = "hello world" prompt: goodbye text = "goodbye" */
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks