11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

106Part II: Becoming a Functional C++ Programmerthe remaining characters are left in the input hopper for the next cin>>statement. Thus, if I were to enter “the Dog”, szString2 would be filledwith “the”, and the word “Dog” would be left in the input buffer.The cin >> extractor knows nothing about the length of the string. cinis perfectly willing to read thousands of characters and stuff them intoszString1, even though it is declared 256 characters long. This causes adangerous overflow condition that hackers can (and will) exploit to put avirus in your program.C++ provides work-arounds for many of the string overflow problems. Forexample, the function getline() inputs a line of text; however, this functionaccepts the length of the string as one of its arguments:cin.getline(string, lengthOfTheString);(Ignore the strange looking cin. format for now.)The strncpy() and strncat() functions accept the length of the targetbuffer as one of their arguments. The call strncpy(szString, szString1,128) says “copy the characters in szString1 into szString until you copya null character or until you’ve copied 128 characters, whichever comesfirst.” The call specifically does not mean copy 128 characters every time.There are both “counting” and “noncounting” versions of most of thestr...() functions. The noncounting versions don’t require the maximumnumber of characters to process as an argument. You can use these whenyou don’t know the buffer size, but be aware that they are perfectly happyto write beyond the end of the target string.String-ing Along VariablesANSI C++ includes a type string designed to make it easier to manipulatestrings of text.I use the term string to refer to an array of characters terminated by a nulland string type to refer to the type string. The string type includes operationsfor copying, concatenating, capitalizing, knotting, and simple magictricks. string avoids the overrun problems inherent with null terminatedstrings. The functions that manipulate string objects are defined in theinclude file .The string type based StringConcatenate program appears as follows:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!