More C Strings Input and Output Functions
For the input function, the gets function is much more simpler to use than the scanf function. The scanf function is often used in the advanced C programs. The same is for the output function. the puts function is more simpler to use than the printf function. Here are the definitions for these functions:
- puts – Put String
- gets – Get String
- fgets – File Get String
As you can see in the above definitions, the fgets function is used to get the value from a file. However, fgets is also often used in place of the gets function because gets is mostly misused by programmers.
Here is the sample code for these functions:
/*
*
* string.c
*
* Program to illustrate the use of gets, puts and fgets
*
* by Mark Virtue, 2001.
*
*/
#include <stdio.h>
#include <string.h>
main() {
char name[21];
puts("This is a basic programn");
fputs("Please enter your full name (20 characters max): ", stdout);
fgets(name, 21, stdin);
fputs("Your full name is ", stdout);
puts(name);
fflush(stdin);
if (strlen(name) >= 20)
while (getchar() != 'n' && getchar() != EOF) {}
getchar();
}
Note that when I used GCC to compile the above code with gets function, the GCC compiler would give me a warning stated that the gets function is dangerous and should not use it. Therefore I recommend to use fgets to make things easier.
Also notice that the above code contains a new function, fputs. As my current knowledge, the difference between fputs and puts is that puts automatically adds a break (n) at the end of each output, whereas fputs does not. The fputs function is good to display the prompt for user to enter the data.