C Programming for the Absolute Beginner phần 7 - Pdf 20

main()

{

char myString[21] = {0};
int iSelection = 0;
int iRand;

srand(time(NULL));

iRand = (rand() % 4) + 1; // random #, 1-4

while ( iSelection != 4 ) {

printf("\n\n1\tEncrypt Clear Text\n");
printf("2\tDecrypt Cipher Text\n");
printf("3\tGenerate New Key\n");
printf("4\tQuit\n");
printf("\nSelect a Cryptography Option: ");
scanf("%d", &iSelection);

switch (iSelection) {

case 1:
printf("\nEnter one word as clear text to encrypt: ");
scanf("%s", myString);
encrypt(myString, iRand);
break;

case 2:
printf("\nEnter cipher text to decrypt: ");

x = 0;
printf("\nEncrypted Message is: ");

//print the encrypted message
while ( sMessage[x] ) {
printf("%c", sMessage[x]);
x++;

} //end loop

} //end encrypt function

void decrypt(char sMessage[], int random)

{

int x = 0;
Chapter 7 • Pointers
175
x = 0;

//decrypt the message by shifting each characters ASCII value
while ( sMessage[x] ) {
sMessage[x] = sMessage[x] - random;
x++;

} //end loop

x = 0;
printf("\nDecrypted Message is: ");

C Programming for the Absolute Beginner, Second Edition
176
Challenges
1. Build a program that performs the following operations:

Declares three pointer variables called
iPtr
of type
int
,
cPtr
of type
char
, and
fFloat
of type
float
.

Declares three new variables called
iNumber
of
int
type,
fNumber
of
float
type, and
cCharacter
of

function, but passed to a new function called
TossDie()
. The
TossDie()
function will take care of generating random numbers
from one to six and assigning them to the appropriate array
element number.
4. Modify the Cryptogram program to use a different type of key
system or algorithm. Consider using a user-defined key or a
different character set.
Chapter 7 • Pointers
177
This page intentionally left blank
8
C HAP TE R
STRINGS
trings use many concepts you have already learned about in this book,
such as functions, arrays, and pointers. This chapter shows you how to
build and use strings in your C programs while also outlining the intimate
relationships strings have with pointers and arrays. You will also learn many new
common library functions for manipulating, converting, and searching strings, as
well as the following:
• Reading and printing strings
• String arrays
• Converting strings to numbers
• Manipulating strings
• Analyzing strings
I
NTRODUCTION TO
S

subsequent memory locations that the pointer variable
myString points to. In other words,
the pointer variable
myString points to the first character in the string "Mike".
CAUTION
TIP
C Programming for the Absolute Beginner, Second Edition
180
To further demonstrate this concept, study the following program and its output in
Figure 8.2, which reveals how strings can be referenced through pointers and traversed sim-
ilar to arrays.
#include <stdio.h>

main()

{

char *myString = "Mike";
int x;

printf("\nThe pointer variable's value is: %p\n", *myString);
printf("\nThe pointer variable points to: %s\n", myString);
printf("\nThe memory locations for each character are: \n\n");

//access & print each memory address in hexadecimal format
for ( x = 0; x < 5; x++ )
printf("%p\n", myString[x]);

} //end main
FIGURE 8.2

C Programming for the Absolute Beginner, Second Edition
182
In the next few sections, you will continue your investigation into strings and their use by
learning how to handle string I/O and how to convert, manipulate, and search strings using
a few old and new C libraries and their associated functions.
R
EADING AND
P
RINTING
S
TRINGS
Chapter 6, “Arrays,” provided you with an overview of how to read and print array contents.
To read and print a character array use the
%s conversion specifier as demonstrated in the
next program.
#include <stdio.h>

main()

{

char color[12] = {'\0'};

printf("Enter your favorite color: ");
scanf("%s", color);

printf("\nYou entered: %s", color);

} //end main
The preceding program demonstrates reading a string into a character array with initialized

This problem occurs because not only must you declare a string as a pointer to a character,
but you must also allocate memory for it. Remember that when first created, a string is noth-
ing more than a pointer that points to nothing valid. Moreover, when the
scanf() function
attempts to assign data to the pointer’s location, the program crashes because memory has
not been properly allocated.
For now, you should simply use initialized character arrays with sufficient memory allocated
to read strings from standard input. In Chapter 10, “Dynamic Memory Allocation,” I will
discuss the secret to assigning data from standard input to strings (pointer variables).
S
TRING
A
RRAYS
Now you know strings are pointers and that strings, in an abstract sense, are arrays of
characters. So, if you need an array of strings, do you need a two-dimensional array or a
single-dimension array? The correct answer is both. You can create an array of strings with
a one-dimensional pointer array and assign string literals to it or you can create a two-
dimensional pointer array, allowing C to reserve enough memory for each character array.
To demonstrate how an array of strings can be created using a single-dimension pointer array
of type
char, study the following program and its output shown in Figure 8.5.
C Programming for the Absolute Beginner, Second Edition
184
#include <stdio.h>

main()

{

char *strNames[5] = {0};


{

char *colors[3][10] = {'\0'};

printf("\nEnter 3 colors seperated by spaces: ");
scanf("%s %s %s", colors[0], colors[1], colors[2]);

printf("\nYour entered: ");
printf("%s %s %s\n", colors[0], colors[1], colors[2]);

}
In the preceding program I declared a 3x10 (three by ten) two-dimensional character array
that reserves enough memory for 30 characters. Notice I only need to tell C to reference the
first dimension of each element in the character array when referencing a single string.
Providing I’ve allocated enough elements in the second dimension, I can easily use
scanf()
to grab text entered by the user. In Chapter 10, I will show you how to grab portions of
contiguous memory without first allocating it in an array.
C
ONVERTING
S
TRINGS TO
N
UMBERS
When dealing with ASCII characters, how do you differentiate between numbers and letters?
The answer is two-fold. First, programmers assign like characters to various data types, such
as characters (
char) and integers (int), to differentiate between numbers and letters. This is a
straightforward and well-understood approach for differentiating between data types. But

x = atof(str1);
y = atoi(str2);

printf("\nString 1 converted to a float is %.2f\n", x);
printf("String 2 converted to an integer is %d\n", y);

} //end main
FIGURE 8.6
Converting string
literals to numeric
types float and
int.
Chapter 8 • Strings
187
When printed to standard output, strings are not surrounded by quotes auto-
matically, as depicted in Figure 8.6. This illusion can be accomplished by using
special quote characters in a
printf() function. You can display quotes in stan-
dard output using a conversion specifier, more specifically the
\" conversion
specifier, as the next print statement demonstrates.
printf("\nString 1 is \"%s\"\n", str1);
You may be wondering why string conversion is so important. Well, for example, attempting
numeric arithmetic on strings can produce unexpected results as demonstrated in the next
program and in Figure 8.7.
#include <stdio.h>

main()

{


int iResult;

iResult = atoi(str1) + atoi(str2);

printf("\nString 1 + String 2 is %d\n", iResult);

} //end main
FIGURE 8.8
Using the atoi
function to
convert strings to
numbers.
M
ANIPULATING
S
TRINGS
A common practice among programmers is manipulating string data, such as copying one
string into another and concatenating (gluing) strings to each other. Also common is the need
to convert strings to either all lowercase or all uppercase, which can be important when
comparing one string to another. I will show you how to perform these string manipulations
in the following sections.
Chapter 8 • Strings
189
strlen()
The string length (strlen()) function is part of the string-handling library <string.h> and is
quite simple to understand and use.
strlen() takes a reference to a string and returns the
numeric string length up to the
NULL or terminating character, but not including the NULL

character to either uppercase or lowercase (notice I said single character). To convert an entire
character array to either all uppercase or all lowercase, you will need to work a little harder.
One solution is to build your own user-defined functions for converting character arrays
to uppercase or lowercase by looping through each character in the string and using the
strlen() function to determine when to stop looping and converting each character to either
lower- or uppercase with
tolower() and toupper(). This solution is demonstrated in the next
program, which uses two user-defined functions and, of course, the character handling func-
tions
tolower() and toupper() to convert my first name to all lowercase and my last name to
all uppercase. The output is shown in Figure 8.10.
#include <stdio.h>
#include <ctype.h>

//function prototypes
void convertL(char *);
void convertU(char *);

main()

{

char name1[] = "Michael";
char name2[] = "Vine";

convertL(name1);
convertU(name2);

} //end main


with functions
tolower() and
toupper().
strcpy()
The strcpy() function copies the contents of one string into another string. As you might
imagine, it takes two arguments and is pretty straightforward to use, as the next program
and Figure 8.11 demonstrate.
#include <stdio.h>
#include <string.h>

C Programming for the Absolute Beginner, Second Edition
192
main()

{

char str1[11];
char *str2 = "C Language";

printf("\nString 1 now contains %s\n", strcpy(str1, str2));

} // end main
FIGURE 8.11
The output of
copying one string
to another using
the strcpy()
function.
The strcpy() function takes two strings as arguments. The first argument is the string to be
copied into and the second argument is the string that will be copied from. After copying

printf("\n%s\n", strcat(str1, str2));

} // end main
As Figure 8.12 demonstrates, the second string argument (str2) is concatenated to the first
string argument (
str1). After concatenating the two strings, the strcat() function returns
the value in
str1. Note that I had to include an extra space at the end of str1 “Computer
Science”, because the
strcat() function does not add a space between the two merged strings.
FIGURE 8.12
Using the
strcat()
function to glue
strings together.
A
NALYZING
S
TRINGS
In the next couple of sections, I will discuss a few more functions of the string-handling library
that allow you to perform various analyses of strings. More specifically, you will learn how to
compare two strings for equality and search strings for the occurrence of characters.
C Programming for the Absolute Beginner, Second Edition
194
strcmp()
The strcmp() function is a very interesting and useful function that is primarily used to com-
pare two strings for equality. Comparing strings is actually a common process for computer
and non-computer uses. To demonstrate, consider an old library card-catalog system that used
human labor to manually sort book references by various keys (author name, ISBN, title, and
so on). Most modern libraries now rely on computer systems and software to automate the

printf("\nLetter A is equal to letter A\n");

Chapter 8 • Strings
195
if ( strcmp(str1, str3) > 0 )
printf("Letter A is greater than character !\n");

if ( strcmp(str3, str1) < 0 )
printf("Character ! is less than letter A\n");

} // end main
FIGURE 8.13
Comparing strings
using the
strcmp()
function.
The strcmp() function takes two strings as arguments and compares them using correspond-
ing character codes. After comparing the two strings, the
strcmp() function returns a single
numeric value that indicates whether the first string is equal to, less than, or greater than
the second string. Table 8.1 describes the
strcmp() function’s return values in further detail.
T
ABLE
8.1 R
ETURN
V
ALUES AND
D
ESCRIPTIONS FOR THE

printf("\nstr2 = %s\n", str2);
printf("\nstr3 = %s\n", str3);

if ( strstr(str1, str2) != NULL )
printf("\nstr2 was found in str1\n");
else
printf("\nstr2 was not found in str1\n");

if ( strstr(str1, str3) != NULL )
printf("\nstr3 was found in str1\n");
else
printf("\nstr3 was not found in str1\n");

} // end main
FIGURE 8.14
Using the
strstr()
function to search
one string for
another.
Chapter 8 • Strings
197
As you can see from the preceding program, the strstr() function takes two strings as argu-
ments. The
strstr() function looks for the first occurrence of the second argument in the
first argument. If the string in the second argument is found in the string in the first argu-
ment, the
strstr() function returns a pointer to the string in the first argument. Otherwise
NULL is returned.
C

"PODSTRINGGDIWHIEEICERLS",
C Programming for the Absolute Beginner, Second Edition
198


Nhờ tải bản gốc
Music ♫

Copyright: Tài liệu đại học © DMCA.com Protection Status