Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C For Dummies 2nd Ed 2004.pdf
Скачиваний:
43
Добавлен:
17.08.2013
Размер:
8.34 Mб
Скачать

Chapter 4: C What I/O 47

A bit of justification

To demonstrate how printf() can format text, as well as use those handy conversion characters and var things I scared you with in the preceding sec­ tion, how about a sample program?

For your consideration is the following source code, which I have named JUSTIFY.C. Marvel at it:

#include <stdio.h>

int main()

{

printf(“%15s”,”right\n”); printf(“%-15s”,”left\n”); return(0);

}

What JUSTIFY.C does is to display two strings: right is right-justified, and left is left-justified. This makes more sense when you see the program’s output rather than just look at the source code.

Enter this source code into your text editor.

In the first printf statement, the first string is %15s (percent sign, 15, little s). That’s followed by a comma and then right, followed by the newline escape sequence, \n (backslash, little n).

The second printf statement is nearly the same thing, though with a minus sign before the 15 and the string left rather than right.

This program contains more C doodads than any other program introduced in the first three chapters in this book. Be careful with what you type! When you’re certain that you have it right, save the file to disk as JUSTIFY.C.

Compile JUSTIFY.C. Fix any errors if you need to. Then run the program. Your output should look something like this:

right

left

The word right is right-justified 15 spaces over; left is left-justified. This arrangement was dictated by the %15s formatting command in printf(). The %15s part of the formatting string didn’t print at all. Instead, it controlled how the other string’s contents appeared on the screen. That’s the formatting power of printf() at work.

48

Part I: Introduction to C Programming

Maybe a little more help in understanding conversion characters

To drive home how printf() uses its format­ ting string and arguments, bring up the source code for the GOODBYE.C program into your text editor. Change Line 5 to read:

printf(“%s”,”Goodbye, cruel world!\n”);

as the original; you have merely used the %s in the printf() function to “format” the output.

Try this modification of Line 5:

printf(“%s, %s %s\n”,”Goodbye”,”cruel”, ”world!”);

printf() has been modified to contain a for­ matting string and an argument.

The formatting string is %s, which is the string (for s) placeholder.

The argument is a string of text: “Goodbye, cruel world\!n”.

Save the source code under a new filename, BYE.C. Compile and run. The output is the same

Carefully edit Line 5 to look like what’s shown in the preceding line. It has three string place­ holders, %s, and three strings in double quotes (with commas between them). Save. Compile. Run. The output should be the same.

(If you get a compiling error, you probably have put a comma inside the double quotes, rather than between them.)

The JUSTIFY.C program shows you only a hint of what the printf() function can do. printf() can also format numbers in a remarkable number of ways, which is a little overwhelming to present right now in this chapter.

In the printf() function, the first item in quotes is a formatting string, though it can also contain text to be displayed right on the screen.

The percent character holds special meaning to printf(). It identifies a conversion character — what I call a “placeholder” — that tells printf how to format its output.

The conversion character s means string: %s.

Any numbers between the % and the s are used to set the width of the text string displayed. So, %15s means to display a string of text using 15 char­ acters. A minus sign before the 15 means to left-justify the string’s output.

Doesn’t “left-justify” sound like a word processing term? Yup! It’s formatting!

printf() doesn’t truncate or shorten strings longer than the width specified in the %s placeholder.

Chapter 4: C What I/O 49

All this conversion-character stuff can get complex. Rest assured that seldom does anyone memorize it. Often, advanced programmers have to consult their C language references and run some tests to see which for­ matting command does what. Most of the time, you aren’t bothered with this stuff, so don’t panic.

scanf Is Pronounced “Scan-Eff”

Output without input is like Desi without Lucy, yang without yin, Caesar salad without the garlic. It means that the seven dwarves would be singing “Oh, Oh, Oh” rather than “I/O, I/O.” Besides — and this may be the most horrid aspect of all — without input, the computer just sits there and talks at you. That’s just awful.

C has numerous tools for making the computer listen to you. A number of commands read input from the keyboard, from commands that scan for indi­ vidual characters to the vaunted scanf() function, which is used to snatch a string of text from the keyboard and save it in the cuddly, warm paws of a string variable.

scanf() is a function like printf(). Its purpose is to read text from the keyboard.

Like the f in printf(), the f in scanf() means formatted. You can use scanf() to read a specifically formatted bit of text from the keyboard. In this chapter, however, you just use scanf() to read a line of text, noth­ ing fancy.

Putting scanf together

To make scanf() work, you need two things. First, you need a storage place to hold the text you enter. Second, you need the scanf function itself.

The storage place is called a string variable. String means a string of characters — text. Variable means that the string isn’t set — it can be what­ ever the user types. A string variable is a storage place for text in your pro­ grams. (Variables are discussed at length in Chapter 8.)

The second thing you need is scanf() itself. Its format is somewhat similar to the advanced, cryptic format for printf(), so there’s no point in wasting any of your brain cells covering that here.

50

Part I: Introduction to C Programming

An example of using scanf() reads in someone’s first name. First, you create a storage place for the first name:

char firstname[20];

This C language statement sets aside storage for a string of text — like creating a safe for a huge sum of money that you wish to have some day. And, just like the safe, the variable is “empty” when you create it; it doesn’t contain anything until you put something there.

Here’s how the preceding statement breaks down:

char is a C language keyword that tells the compiler to create a character variable, something that holds text (as opposed to numbers).

firstname is the name of the storage location. When the source code refers to the variable, it uses this name, firstname.

[20] defines the size of the string as being able to hold as many as 20 characters. All told, you have set aside space to hold 20 characters and named that space — that variable firstname.

The semicolon ends the C language statement.

The next step is to use the scanf() function to read in text from the keyboard and store it in the variable that is created. Something like the following line would work:

scanf(“%s”,&firstname);

Here’s how this statement works:

scanf() is the function to read information from the keyboard.

%s is the string placeholder; scanf() is looking for plain old text input from the keyboard. Pressing the Enter key ends input.

The text input is stored in the string variable named firstname. The ampersand is required here to help scanf() find the location of the string variable in memory.

The semicolon ends the C language statement.

Between the variable and scanf(), text is read from the keyboard and stored in the computer’s memory for later use. The next section coughs up an example.