This item was added on: 2003/02/07
To obtain a line of text from the user via the keyboard, there are a few standard functions available. These include:
char *fgets(char *s, int size, FILE *stream);
int scanf( const char *format, ...);
char *gets(char *s);
The first on the list, fgets(), it the best function to use, as it provides control over how many characters are actually read into memory. The scanf() function can be used to do this too, but it is really designed for use with formatted input. By this I mean a data stream that is in a guaranteed format, which is something a user with a keyboard can rarely provide with any accuracy The gets() function is old, and should not be used. It doesn't control the number of characters it reads in, and will happily overwrite memory it doesn't own if the user provides an unexpectedly long line of input. In other words, gets is very dangerous.
fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A '\0' is stored after the last character in the buffer.
One problem that people find with fgets(), is that it may place the newline character \n ([Enter]) into the buffer. That is, if there is enough room to store the newline in the array, it will. This can cause problems with string comparisons, file names, and a number of other things you use your input for. An example of this problem would be passing the array to the fopen() function to open a file stream. The newline character would be taken as part of the file name itself, and the operating system would look for a file named myfile.dat\n. Of course, when debugging, it can be easy to miss this, as the variable contents is printed normally on the screen.
Here is an example of how to use fgets(). It shows how to remove the newline from the end of the array. Remember, it is important to check for the existence of this character before wiping it out with a \0, as it is not always there.
Note the position of the < and > signs in the output. These help show the presence of the newline character in the buffer.
printf ("Please enter a line of text, max %d characters\n", sizeof(buf));
if (fgets(buf, sizeof(buf), stdin) != NULL)
printf ("Thank you, you entered >%s<\n", buf);
if ((p = strchr(buf, '\n')) != NULL)
*p = '\0';
printf ("And now it's >%s<\n", buf);
In case you're wondering, BUFSIZ is a standard name, defined in stdio.h. You don't need to define it yourself, but you should be aware that your compiler's version of it might not be the same value as shown here.