How to Display Text On-Screen in C with puts() and printf()

The things that a C program can do are limitless, but when you're first learning the language, you need to start small. One of the most common functions you'll want your C program to do is display text on the screen, and there are two ways to do so: puts() and printf().

puts()

Puts probably stands for put string, where a string is a bit of text you put to the screen. Regardless, here's how it works:

puts("Greetings, human!");

The text to display — the string — is enclosed in the function's parentheses. Furthermore, it's enclosed in double quotes, which is how you officially create text inside the C language, and how the compiler tells the difference between text and programming statements. Finally, the statement ends in a semicolon.

Here's how puts() might fit into some simple source code:

int main()
{
    puts("Greetings, human!");
    return(0);
}

The puts() function works inside the main() function. It's run first, displaying the text Greetings, human! on the screen. Then the return(0); statement is run next, which quits the program and returns control to the operating system.

printf()

Another C language function that displays text on the screen is printf(), which is far more powerful than puts() and is used more often. While the puts() function merely displays text on the screen, the printf() function displays formatted text. This gives you more control over the output.

Try the following source code:

 #include <stdio.h>
int main()
{
    printf("Sorry, can't talk now.");
    printf("I'm busy!");
    return(0);
}

Type this code into your editor and save it to disk as HELLO.C. Then compile it and run it.

Sorry, can't talk now.I'm busy!

You probably assumed that by putting two printf() statements on separate lines, two different lines of text would be displayed. Wrong!

The puts() function automatically appends a newline character at the end of any text it displays; the printf() function does not. Instead, you must manually insert the newline character (\n) into your text.

To "fix" the line breaks in the preceding HELLO.C file, change line 5 as follows:

printf("Sorry, can't talk now.\n");

The escape sequence \n is added after the period. It's before the final quotation marks because the newline character needs to be part of the string that's displayed.

So save the change, recompile HELLO.C, and run it. Now the output is formatted to your liking:

Sorry, can't talk now.
I'm busy!
  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com