c for engineers and scientists introduction to programming with ansi c phần 8 ppt

67 488 0
c for engineers and scientists introduction to programming with ansi c phần 8 ppt

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

452 Chapter Ten Pointers declaration for the function can be either an array declaration or a pointer declaration. Thus, the following argument declarations are equivalent: float a[ ]; float *a; 7. Pointer variables can be incremented, decremented, and compared. Numbers added to or subtracted from a pointer are automatically scaled. The scale factor used is the number of bytes required to store the data type originally pointed to. Character Strings .Chapter Eleven 11.1 String Fundamentals 11.2 Pointers and Library Functions 11.3 String Definitions and Pointer Arrays 11.4 Formatting Strings 11.5 Common Programming Errors 11.6 Chapter Summary 453 454 Chapter Eleven Character Strings On a fundamental level, strings are simply arrays of characters that can be manipulated using standard element-by-element array-processing techniques. On a higher level, string library functions are available for treating strings as complete entities. This chapter explores the input, manipulation, and output of strings using both approaches. We will also examine the close connection between string-handling functions and pointers. 11.1 String Fundamentals A string constant, informally referred to as a string, is any sequence of characters enclosed in double quotes. For example, "This is a string", "Hello World! ", and" xyz 123 *! #@&" are all strings. A string is stored as an array of characters terminated by a special end-of- string marker called the null character. The null character, represented by the escape sequence \ 0, is the sentinel marking the end of the string. For example, Figure 11-1 illustrates how the string "Good Morning!" is stored in memory. The string uses fourteen storage locations, with the last character in the string being the end-of-string marker \ o. The double quotes are not stored as part of the string. Since a string is stored as an array of characters, the individual characters in the array can be input, manipulated, or output using standard array-handling techniques utilizing either subscript or pointer notations. The end-of-string null character is useful as a sentinel for detecting the end of the string. String Input and Output Although the programmer has the choice of using either a library or a user-writ- ten function for processing a string already in memory, inputting a string from a keyboard or displaying a string always requires some reliance on standard library functions. Table 11-1 lists the commonly available library functions for both character-by-character and complete string input/ output. FIGURE 11-1 Storing a String in Memory TABLE 11-1 Standard String or Character Library Functions Input gets ( scanf ( ) get char ( Output puts( ) printf ( putchar( ) 11.1 String Fundamentals The gets ( ) and puts ( ) functions deal with strings as complete units. Both are written using the more elemental routines getchar ( ) and put char ( ). The getchar ( ) and put char ( ) routines provide for the input and output of individual characters. Programs that access any of these four routines must con- tain the stdio. h header file, which contains definitions required by the accessed library functions. Program 11-1illustrates the use of get s ( ) and puts ( ) to input and output a string entered at the user's terminal. JPI, Program 11-1 455 #include <stdio.h> main( ) { char message[81]; /* enough storage for a complete line */ printf("Enter a string:\n"); gets (message) ; printf("The string just entered is:\n"); puts(message); The following is a sample run of Program 11-1: Enter a string: This is a test input of a string of characters. The string just entered is: This is a test input of a string of characters. The gets ( ) function used in Program 11-1continuously accepts and stores the characters typed at the terminal iato the character array named message. Pressing the ENTERkey at the terminal generates a newline character, \n, which is interpreted by gets ( ) as the end-of-character entry. All the characters encountered by gets ( ), except the newline character, are stored in the mes- sage array. Beforereturning, the gets ( ) function appends the null character to the stored set of characters, as illustrated in Figure 11-2a. The pu t s ( ) function is then used to display the string. As illustrated in Figure 11-2b, the puts ( ) function automatically sends a newline escape sequence to the display terminal after the string has been printed. In general, aprintf ( ) function call can always be used in place ofa puts ( ) function call. For example, the statement printf ("%s\n" ,message); is a direct replacement for the statement puts (message) ; used in Program 11-1. The newline escape sequence in the printf ( ) function call substitutes for the automatic newline generated by puts ( ) after the string is displayed. The one-to-one correspondence between the output functions printf ( ) artd puts ( ) is not duplicated by the input functions scanf ( ) and gets ( ). For 456 (a) (b) characters \ n characters \ 0 Chapter Eleven Character Strings •. _I __ g_e_t_s_(_)__ 1•.~ characters \ 0 •. _1 __ p_u_t_S_(_)__ 1 characters \n FIGURE 11-2 Inputting and Outputting a String Using the gets ( ) and puts ( ) Functions example, scanf (" %s",message) and gets (message) are not equivalent. The scanf ( ) function reads a set of characters up to either a blank space or a newline character, whereas gets ( ) stops accepting characters only when a newline is detected. Trying to enter the characters This is a string using the statement scanf (" %s",message) ; results in the word This being assigned to the message array. Entering the complete line using a scanf ( ) function call would require a statement such as: scanf("%s %s %s %s"; messagel, message2, message3, message4); Here, the word This would be assigned to the string messagel, the word is assigned to the string message2, and so on. The fact that a blank is used as a delimiter by scanf ( ) means that this function isn't that useful for entering string data. Note that if the scanf ( ) function is used for inputting string data, the &is not used before the array name. Since an array name is a pointer constant equiva- lent to the address of the first storage location reserved for the array, message is the same as &message [0]. Thus, the function call scanf (" %s" , &mes- sage [0] ) can be replaced by scanf ("%s" ,message). String Processing Strings can be manipulated using either standard library functions or standard array-processing techniques. The library functions typically available for use are presented in the next section. For now we will concentrate on processing a string in a character-by-character fashion. This will allow us to understand how the standard library functions are constructed and to create our own library func- tions. For a specific example, consider the function strcopy ( ) that copies the contents ofstring2 to string1. strcopy(char stringl[], char string2[]) { /* copy string2 to stringl */ int i 0; /* i will be used as a subscript */ while string2[i]!= '\0') /* check for the end-of-string */ stringl[i] = string2[i]; /* copy the element to stringl */ ++i; } stringl[i] return; , \0' ; /*terminate the first string */ 11.1 String Fundamentals Although this string copy function can be shortened considerably and written: more compactly, the function illustrates the main features of string manipulation. The two strings are passed to strcopy1 as arrays. Each element of string2 is then assigned to the equivalent element of string1 until the end-of-string marker is encountered. The detection of the null character forces the termination of the while loop controlling the copying of elements. Since the null character is not copied from string2 to string1, the last statement in strcopy ( ) appends an end-of-string character to stringl. Prior to calling strcopy ( ), the programmer must ensure that sufficient space has been allocated for the string1 array to accomodate the elements of the string2 array. Program 11-2 includes the strcopy ( ) function in a complete program. Notice that the function prototype for strcopy ( ) in main ( ) declares that the function expects to receive the addresses of the beginnings of two character arrays. ,101, Program 11-2 457 #include <stdio.h> main ( ) { char message[81]; char new_mess[81]; int i; void strcopy(char [ /* enough storage for a complete line */ /* enough storage for a copy of message */ ], char [ ]); /* function prototype */ printf ("Enter a sentence: "); gets (message) ; strcopy(new_mess,message); /* pass two array addresses */ puts(new_mess); void strcopy(char stringl[], char string2[]) /* copy string2 to stringl */ int i o. , /* i will be used as a subscript */ while string2[i] != '\0') /* check for the end-of-string */ stringl[i] = string2[i]; /* copy the element to stringl */ ++i; } stringl[i] return; '\0' ; /* terminate the first string */ The following is a sample run of Program 11-2: Enter a sentence: How much wood could a woodchuck chuck. How much wood could a woodchuck chuck. 458 Chapter Eleven Character Strings Character-by-Character Input Just as strings can be processed using character-by-character techniques, they can be entered and displayed in this manner. For example, consider Program 11-3, which uses the character-input function getchar ( ) to construct a string one character at a time. The boxed portion of Program 11-3 essentially replaces the gets ( ) function previously used in Program 11-1. }ql, Program 11-3 #include <stdio.h> main( ) { char message[81],c; int i; /* enough storage for a complete line */ printf("Enter a sentence:\n"); i = 0; while( i < 81 && (c { message[i] = c; ++i; } message[i] = '\0'; get char ( )) ! = '\n') /* store the character entered */ /* terminate the string */ printf("The sentence just entered is:\n"); puts(message); The following is a sample run of Program 11-3: Enter a string: This is a test input of a string of characters. The string just entered lS: This is a test input of a string of characters. The whi 1e statement in Program 11-3causes characters to be read providing the number of characters entered is less than 81 and the character returned by getchar ( ) is not the newline character. The parentheses around the expression c = getchar ( ) are necessary to assign the character returned by get char ( ) to the variable c prior to comparing it to the newline escape sequence. Otherwise, the comparison operator, ! =, which takes precedence over the assign- ment operator, causes the entire expression to be equivalent to c = (getchar() != '\n') 11.1 String Fundamentals This has the effect of first comparing the character returned by getchar to ,\n '. The value of the relational expression get char () ! = I \n' is either 0 or 1, depending on whether or not getchar ( ) received the newline character. The value assigned to c then would also be either 0 or 1, as determined by the comparison. Program 11-3 also illustrates a very useful technique for developing functions. The boxed statements constitute a self-contained unit for enter- ing a complete line of characters from a terminal. As such, these statements can be removed from main ( ) and placed together as a new function. Pro- gram 11-4 illustrates placing these statements in a new function called get ~ line ( ). }Ol, Program 11-4 459 #include <stdio.h> main( ) { char message[81]i int ii void getline(char /* enough storage for a complete line: * / ]) i /* function prototype */ printf("Enter a string:\n"); getline(message)i printf("The string just entered is:\n")i puts (message) ; void getline(char strng[ ]) int i = Oi char Ci while( i < 81 && (c = get char ( )) != '\n') { strng[i] = Ci ++ii /* store the character entered */ } strng[i] returni , \0' ; /* terminate the string */ We can go further with getline ( ) and write it more compactly by having the character returned by get char ( ) assigned directly to the strng array. This eliminates the need for the local variable c and results in the follow- ing version: 460 Chapter Eleven Character Strings getline(char strng[ ]) { int i = 0; while ( i < 81 && (strng[i++] = get char ( )) != 'In') strng[i] return; '\0' ; 1* terminate the string *1 Notice that in addition to assigning the returned character from getchar ( directly to the strng array, the assignment statement strng[i++] = getchar( additionally increments the subscript i using the postfix operator, ++. The null statement, ;, then fulfills the requirement that a while loop contain at least one statement. Both versions of getline ( ) are suitable replacements for gets ( ), and show the interchangeability between user-written and library functions. C's enormous flexibility is shown by this ability to replace a library function with a user-written version and its ability to have functions written in various ways. Neither version of get 1ine ( ) is "more correct" from a programming standpoint. Each version presented (and more versions can be created) has its advantages and disadvantages. While the second version is more compact, the first version is clearer to beginning programmers. In creating your own C pro- grams, select a style that is comfortable and remain with it until your growing programming expertise dictates modifications to your style. Exercises 11.1 la. The following function can be used to select and display all vowels contained within a user-input string: vowels(char strng[ ]) { int i = 0; char c; while ((c strng[i++])!= '\0') switch(c) { case 'a I: case 'e': case'i' : case '0': case 'u': putchar(c); } /* end of switch */ putchar ( ,\n ' ) ; 11.2 Pointers and Library Functions Notice that the switch statement in vowels ( ) uses the fact that selected cases "drop through" in the absence of break statements. Thus, all selected cases result in a put char ( ) function call. Include vowels ( ) in a working program that accepts a user-input string and then displays all vowels in the string. In response to the input How much is the little worth worth?, your program should display ouieieoo. b. Modify vowels ( ) to count and display the total number of vowels contained in the string passed to it. 2. Modify the vowels ( ) function given in Exercise la to count and display the individual numbers of each vowel contained in the string. 3.a. Write a C function to count the total number of characters, including blanks, contained in a string. Do not include the end-of-string marker in the count. b. Include the function written for Exercise 3a in a complete working program. 4. Write a program that accepts a string of characters from a terminal and displays the hexadecimal equivalent of each character. 5. Write a C program that accepts a string of characters from a terminal and displays the string one word per line. 6. Write a function that reverses the characters in a string. (Hint: This can be considered as a string copy starting from the back end of the first string.) 7. Write a function called del_char ( ) that can be used to delete characters from a string. The function should take three arguments: the string name, the number of characters to delete, and the starting position in the string where characters should be deleted. For example, the function call del_char (strng, 13,5) , when applied to the string all enthusiastic people, should result in the string all people. 8. Write a function call add_char ( ) to insert one string of characters into another string. The function should take three arguments: the string to be inserted, the original string, and the position in the original string where the insertion should begin. For example, the call add_char ( "for all", message, 6) should insert the characters for all in message starting at message [5] . 9a. Write a C function named to_upper ( ) that converts lowercase letters into uppercase letters. The expression c - 0 a 0 + 'A' can be used to make the conversion for any lowercase character stored in c. b. Add a data input check to the function written in Exercise 9a to verify that a valid lowercase letter is passed to the function. A character is lowercase if it is greater than or equal to a and less than or equal to z. If the character is not a valid lowercase letter, have the function to_upper ( ) return the passed character unaltered. c. Write a C program that accepts a string from a terminal and converts all lowercase letters in the string to uppercase letters. 10. Write a C program that counts the number of words in a string. A word is encountered whenever a transition from a blank space to a nonblank character is encountered. Assume the string contains only words separated by blank spaces. 11.2 Pointers and LibraryFunctions Pointers are exceptionally useful in constructing string-handling functions. When pointer notation is used in place of subscripts to access individual characters in a string, the resulting statements are both more compact and more efficient. In this section we describe the equivalence between subscripts and pointers when accessing individual characters in a string. 461 [...]... The second common error occurs when an attempt is made to initialize a local array of characters when using a non -ANSI C compiler Only static local arrays can be initialized in non -ANSI C compilers Under the ANSI C standard, the local arrays do not have to be static to be initialized within their declaration statements (Both ANSI and non -ANSI C compilers permit character pointers to be initialized without... indirection operator, *, and the increment operator, ++, have the same precedence These operators associate from left to right, so the character pointed to is accessed before the pointer is incremented Only after completion of the assignment *stringl = *string2 are the pointers incremented to correctly point to the next characters in the respective strings Most C compilers include a string copy function... 'z') The to_ upper ( ) function takes each character passed to it and first examines it to determine if the character is a lowercase letter (a lowercase letter is any character between a and z, inclusive) Assuming that characters are stored using the standard ASCII character codes, the expression let ter - 'a' + 'A' converts a lowercase letter to its uppercase equivalent Rewrite the convert ( ) function... in a character-by-character manner, usually using pointers I 7 String storage can be created by declaring an array of characters or a pointer to a character A pointer to a character can be assigned a string directly String assignment to a string declared as an array of characters is invalid except within a declaration statement 8 Arrays can be initialized using a string assignment of the form char... called This means that if a library function returns a value the function must be declared within your program before it is called For example, if a library function named strngfoo ( ) returns a pointer to a character, the calling TABLE 11-2 String and Character Library Routines Name Description strcat(stringl,string2) Concatenates strchr(string,character) Locates the position of the first occurence...462 Chapter Eleven Character Strings Consider the strcopy ( ) function introduced in the previous section This function was used to copy the characters of one string to a second string For convenience, this function is repeated below: strcopy(char stringl[ ], char string2[ ]) /* copy string2 to stringl */ { int i 0; while string2 [i] ! = stringl[i] = '\ 0' ) string2[i]; /* check for the end-of-string... employee record consisting of the following data items: Name: Identification Number: Regular Pay Rate: Overtime Pay Rate: A suitable declaration for these data items is: struct pay_rec char name[20J; 1 This is true for ANSI C compilers For non -ANSI C compilers the keyword static must be placed before the keyword struct for initialization within the declaration statement This is because static local structures... is that logical groups of data headings can be collected together and accessed with one array name For example, the months in a year can be collectively grouped in one array called months, and the days in a week collectively grouped together in an array called days The grouping of like headings allows the programmer to access and print an appropriate heading by simply specifying the correct position... whereas automatic local structures cannot be initialized 12.1 485 Single Structures int id_num; float reg_rate; float at_rate; }; Once the template for pay _rec is declared, a specific structure using the pay _rec template can be defined and initialized For example, the definition struct pay_rec employee = {"H Price",12 387 ,15 .89 ,25.50}; creates a structure named employee using the pay _rec template... the user to enter these items for five different stocks, each time using the same structure to store the entered data When the data have been entered for a particular stock, have the program compute and display the anticipated stock price based on the entered earnings and price-per-earnings values For example, if a user entered the data XYZ 1.56 12, the anticipated price for a share of XYZ stock is (1.56) . sentence: How much wood could a woodchuck chuck. How much wood could a woodchuck chuck. 4 58 Chapter Eleven Character Strings Character-by-Character Input Just as strings can be processed using character-by-character. Routines Name strcat(stringl,string2) strchr(string,character) strcmp(stringl,string2) strcpy(stringl,string2) strlen(string) isalpha(character) isupper(character) islower(character) isdigit(character) toupper(character) tolower(character) Description Concatenates string2 to stringl. Locates the position of the first occurence. lowercase letters into uppercase letters. The expression c - 0 a 0 + 'A' can be used to make the conversion for any lowercase character stored in c. b. Add a data input check to the function

Ngày đăng: 12/08/2014, 09:22

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan