How to Add Library Functions in C++

By Stephen R. Davis

The C++ programmer is often required to manipulate zero-terminated strings. C++ provides a number of standard string-manipulation functions to make the job easier. A few of these functions are listed in this table.

String-Handling Functions
Name Operation
int strlen(string) Returns the number of characters in a string (not including the
terminating null).
char* strcpy(target, source) Copies the source string into a target array.
char* strcat(target, source) Concatenates the source string onto the end of the target
string.
char* strncpy(target, source, n) Copies a string up to n characters
from the source string into a target array.
char* strncat(target, source, n) Concatenates the source string onto the end of the target
string or n characters, whichever comes
first.
char* strstr(string, pattern) Returns the address of the first occurrence of pattern in
string. Returns a null if pattern is not found.
int strcmp(source1, source2) Compares two strings. Returns –1 if source1 occurs before source2 in the dictionary and 1 if later.
Returns 0 if the two strings match exactly.
int strncmp(source1, source2, n) Compares the first n characters in
two strings.

You need to add the statement #include <cstring> to the beginning of any program that uses a str… function because this include file contains the prototype declarations that C++ requires to check up on your work.

The arguments to the str…() functions appear backward to any reasonable individual. For example, the function strcat(target, source) tacks the second string source onto the end of the first argument target.

The strncpy() and strncat() functions are similar to their strcpy() and strcat() counterparts except that they accept the length of the target buffer as one of their arguments. The call strncpy(szTarget, szSource, 128) says “copy the characters in szSource into szTarget until you copy a null character or until you’ve copied 128 characters, whichever comes first.” This avoids inadvertently writing beyond the end of the source string array.