String Output in C

Now let’s move from string input to string output. Again, we will use library functions. C has three standard library functions for printing strings: puts(), fputs(), and printf().

The puts() Function

The puts() function is very easy to use. Just give it the address of a string for an argument. Following example illustrates some of the many ways to do this.

#include <stdio.h>

#define DEF "I am a #defined string."

int main(void)
{
    char str1[80] = "An array was initialized to me.";
    const char * str2 = "A pointer was initialized to me.";
    puts("I'm an argument to puts().");
    puts(DEF);
    puts(str1);
    puts(str2);
    puts(&str1[5]);
    puts(str2+4);
    getchar();
    return 0;
}

The fputs() Function

The fputs() function is the file-oriented version of gets(). The main differences are these:
 
The fputs() function takes a second argument indicating the file to which to write. You can use stdout (for standard output), which is defined in stdio.h, as an argument to output to your display.
 
Unlike puts(), fputs() does not automatically append a newline to the output.
 
Note that gets() discards a newline on input, but puts() adds a newline on output. On the other hand, fgets() stores the newline on input, and fputs() doesn’t add a newline on output. Suppose you want to write a loop that reads a line and echoes it on the next line. You can do this:

char line[81];
while (gets(line))
    puts(line);

Recall that gets() returns the null pointer if it encounters end-of-file. The null pointer evaluates as zero, or false, so that terminates the loop. Or you can do this:

char line[81];
while (fgets(line, 81, stdin))
    fputs(line, stdout);

With the first loop, the string in the line array is displayed on a line of its own because puts() adds a newline. With the second loop, the string in the line array is displayed on a line of its own because fgets() stores a newline. Note that if you mix fgets() input with puts() output, you’d get two newlines displayed for each string. The point is that puts() is designed to work with gets(), and fputs() is designed to work with fgets().

The printf() Function

Like puts(), it takes a string address as an argument. The printf() function is less convenient to use than puts(), but it is more versatile because it formats various data types.

One difference is that printf() does not automatically print each string on a new line. Instead, you must indicate where you want new lines. Therefore,

printf("%s\n", string);

has the same effect as

puts(string);

As you can see, the first form takes more typing. It also takes longer for the computer to execute (not that you would notice). On the other hand, printf() makes it simple to combine strings for one line of printing. For example, the following statement combines Well, with the user’s name and a #defined character string, all on one line:

printf("Well, %s, %s\n", name, MSG);