Sams Teach Yourself C in 24 Hours (38 page)

BOOK: Sams Teach Yourself C in 24 Hours
9.04Mb size Format: txt, pdf, ePub
ads

17 067231861x CH13 1/25/00 10:29 AM Page 218

218

Hour 13

A null character is automatically appended to the array after the string is read.

Note that with scanf(), unlike printf(), you must pass pointers to your arguments so that the scanf() function can modify their values.

The program in Listing 13.5 shows how to use various format specifiers with the scanf() function.

LISTING 13.5

Using the scanf() Function with Various Format Specifiers

1: /* 13L05.c: Using scanf() */

2: #include

3:

4: main()

5: {

6: char str[80];

7: int x, y;

8: float z;

9:

10: printf(“Enter two integers separated by a space:\n”);

11: scanf(“%d %d”, &x, &y);

12: printf(“Enter a floating-point number:\n”);

13: scanf(“%f”, &z);

14: printf(“Enter a string:\n”);

15: scanf(“%s”, str);

16: printf(“Here are what you’ve entered:\n”);

17: printf(“%d %d\n%f\n%s\n”, x, y, z, str);

18: return 0;

19: }

The following output is displayed on the screen after I run the executable 13L05.exe and enter data (which appears in bold) from my keyboard:

Enter two integers separated by a space:

OUTPUT

10 12345

Enter a floating-point number:

1.234567

Enter a string:

Test

Here are what you’ve entered:

10 12345

1.234567

Test

In Listing 13.5, there are one char array (str), two int variables (x and y), and a
ANALYSIS
float variable declared in lines 6–8.

17 067231861x CH13 1/25/00 10:29 AM Page 219

Manipulating Strings

219

Then, the scanf() function in line 11 reads in two integers entered by the user and saves them into the memory locations reserved for the integer variables x and y. The address-of operator is used to obtain the memory addresses of the variables. The statement in line 13 reads and stores a floating-point number into z. Note that the format specifiers, %d and

%f, are used to specify proper formats for entered numbers in lines 11 and 13.

Line 15 uses the scanf() function and the format specifier %s to read a series of characters entered by the user, and then saves the characters (plus a null character as the terminator) into the array pointed to by str. The address-of operator is not used here, since str itself points to the starting address of the array.

To prove that the scanf() function reads all the numbers and characters entered by the user, the printf() function in line 17 displays the contents saved in x, y, z, and str on the screen. Sure enough, the result shows that the scanf() has done its job.

One thing you need to be aware of is that the scanf() function doesn’t actually start reading the input until the Enter key is pressed. Data entered from the keyboard is placed in an input buffer. When the Enter key is pressed, the scanf() function looks for its input in the buffer. You’ll learn more about buffered input and output in Hour 21,

“Reading and Writing with Files.”

Summary

In this lesson you learned the following important functions and concepts about strings in C:

• A string is a character array with a null character marking the end of the string.

• A string constant is a series of characters enclosed by double quotes.

• The C compiler automatically appends a null character to a string constant that has been used to initialize an array.

• You cannot assign a string constant to a dereferenced char pointer.

13

• The strlen() function can be used to measure the length of a string. This function does not count the null character.

• You can copy a string from one array to another by calling the C function strcpy().

• The gets() function can be used to read a series of characters. This function stops reading when the newline character or end-of-file (EOF) is encountered. The function adds a null character to the end of the string.

17 067231861x CH13 1/25/00 10:29 AM Page 220

220

Hour 13

• The puts() function sends all characters, except the null character, in a string to the stdout, and appends a newline character to the output.

• You can read different data items with the scanf() function by using various format specifiers.

In the next lesson you’ll learn about the concepts of scope and storage in C.

Q&A

Q What is a string? How do you know its length?

A
In C, a string is stored in a character array and is terminated by a null character (‘\0’). The null character tells the string functions (such as puts() and strcpy that they have reached the end of the string.

The C function strlen() can be used to measure the length of a string. If it is successful, the strlen() function returns the total number of bytes taken by the string; however, the null character in the string is not counted.

Q What are the main differences between a string constant and a character
constant?

A
A string constant is a series of characters enclosed by double quotes, while a character constant is a single character surrounded by single quotes. The compiler will append a null character to the string when it is used to initialize an array.

Therefore, an extra byte has to be reserved for the null character. On the other hand, a character constant takes only 1 byte in memory and is not stored in an array.

Q Does the
gets()
function save the newline character from the standard input
stream?

A
No. The gets() function keeps reading characters from the standard input stream until a newline character or end-of-file is encountered. Instead of saving the newline character, the gets() function appends a null character to the string and stores it in the array that is referenced by the argument to the gets() function.

Q What types of data can the
scanf()
function read?

A
Depending on the printf()-style format specifiers that you pass to the function, scanf() can read various types of data, such as a series of characters, integers, or floating-point numbers. Unlike gets(), scanf() stops reading the current input item (and moves to the next input item if there is any) when it encounters a space, a newline, a tab, a vertical tab, or a form feed.

17 067231861x CH13 1/25/00 10:29 AM Page 221

Manipulating Strings

221

Workshop

To help solidify your understanding of this hour’s lesson, you are encouraged to answer the quiz questions and finish the exercises provided in the workshop before you move to the next lesson. The answers and hints to the questions and exercises are given in Appendix B, “Answers to Quiz Questions and Exercises.”

Quiz

1. In the following list, which statements are legal?

• char str1[5] = “Texas”;

• char str2[] = “A character string”;

• char str3[2] = “A”;

• char str4[2] = “TX”;

2. Given a char pointer variable ptr_ch, are the following statements legal?

• *ptr_ch = ‘a’;

• ptr_ch = “A character string”;

• ptr_ch = ‘x’;

• *ptr_ch = “This is Quiz 2.”;

3. Can the puts() function print out the null character in a character array?

4. Which format specifier do you use with the scanf() function to read in a string, and which one do you use to read a floating-point number?

Exercises

1. Given a character array in the following statement,

char str1[] = “This is Exercise 1.”;

write a program to copy the string from str1 to another array, called str2.

13

2. Write a program to measure the length of a string by evaluating the elements in a character array one by one until you reach the null character. To prove you get the right result, you can use the strlen() function to measure the same string again.

3. Rewrite the program in Listing 13.4. This time, convert all uppercase characters to their lowercase counterparts.

4. Write a program that uses the scanf() function to read in two integers entered by the user, adds the two integers, and then prints out the sum on the screen.

17 067231861x CH13 1/25/00 10:29 AM Page 222

18 067231861x CH14 4.10.2000 11:03 AM Page 223

HOUR 14

Understanding Scope

and Storage Classes

Nobody owns anything and all anyone has is the use of his presumed

possessions.

—P. Wylie

In the previous hours, you learned how to declare variables of different data types, as well as to initialize and use those variables. It’s been assumed that you can access variables from anywhere. Now, the question is: Can you

declare variables that are accessible only to certain portions of a program? In this lesson you’ll learn about the scope and storage classes of data in C. The main topics covered in this lesson are

• Block scope

• Function scope

• File scope

• Program scope

18 067231861x CH14 4.10.2000 11:03 AM Page 224

224

Hour 14

• The auto specifier

• The static specifier

• The register specifier

• The extern specifier

• The const modifier

• The volatile modifier

Hiding Data

To solve a complex problem in practice, the programmer normally breaks the problem into smaller pieces and deals with each piece of the problem by writing one or two functions (or routines). Then, all the functions are put together to form a complete program that can be used to solve the complex problem.

In the complete program, there might be variables that have to be shared by all the functions. On the other hand, the use of some other variables might be limited to only certain functions. That is, the visibility of those variables is limited, and values assigned to those variables are hidden from many functions.

Limiting the scope of variables is very useful when several programmers are working on different pieces of the same program. If they limit the scope of their variables to their pieces of code, they do not have to worry about conflicting with variables of the same name used by others in other parts of the program.

In C, you can declare a variable and indicate its visibility level by designating its scope.

Thus, variables with local scope can only be accessed within the block in which they are declared.

The following sections teach you how to declare variables with different scopes.

Block Scope

In this section, a
block
refers to any sets of statements enclosed in braces ({ and }). A variable declared within a block has
block scope
. Thus, the variable is active and accessible from its declaration point to the end of the block. Sometimes, block scope is also called
local scope
.

For example, the variable i declared within the block of the following main function has block scope:

int main()

{

int i; /* block scope */

18 067231861x CH14 4.10.2000 11:03 AM Page 225

Understanding Scope and Storage Classes

225

.

.

.

return 0;

}

Usually, a variable with block scope is called a
local variable
. Note that local variables must be declared at the beginning of the block, before other statements.

Nested Block Scope

You can also declare variables within a nested block. If a variable declared in the outer block shares the same name with one of the variables in the inner block, the variable within the outer block is hidden by the one within the inner block. This is true for the scope of the inner block.

Listing 14.1 shows an example of variable scopes in nested blocks.

TYPE

LISTING 14.1

Printing Variables with Different Scope Levels

1: /* 14L01.c: Scopes in nested block */

2: #include

3:

4: main()

5: {

6: int i = 32; /* block scope 1*/

7:

8: printf(“Within the outer block: i=%d\n”, i);

9:

10: { /* the beginning of the inner block */

11: int i, j; /* block scope 2, int i hides the outer int i*/

12:

13: printf(“Within the inner block:\n”);

14: for (i=0, j=10; i<=10; i++, j--)

15: printf(“i=%2d, j=%2d\n”, i, j);

16: } /* the end of the inner block */

17: printf(“Within the outer block: i=%d\n”, i);

18: return 0;

19: }

The following output is displayed on the screen after the executable (14L01.exe) of the program in Listing 14.1 is created and run:

14

Within the outer block: i=32

OUTPUT
Within the inner block:

i= 0, j=10

BOOK: Sams Teach Yourself C in 24 Hours
9.04Mb size Format: txt, pdf, ePub
ads

Other books

Five Days Dead by Davis, James
April Kihlstrom by The Dutiful Wife
Some Kind of Angel by Larson, Shirley
Candy Kisses by Marie, Bernadette
Cadenas rotas by Clayton Emery
Ninepins by Rosy Thorton
Babel Found by Matthew James
The Darkest Fire by Gena Showalter


readsbookonline.com Copyright 2016 - 2024