// Example to demonstrate some of the cstring functions
// and the usage of cstring parameters in a function.
#include <iostream>
#include <cstring>
using namespace std;
void string_copy(char target[ ], const char source[ ], int target_size);
//Precondition: target_size is the declared size of the string variable
//target. The array source contains a string value terminated with '\0'.
//Postcondition: The value of target has been set to the string value in
//source, provided the declared size of target is large enough.
//If target is not large enough to hold the entire string, a string equal
//to as much of the value of source as will fit is stored in target.
int main( )
{
char short_string[11]; //Can hold strings of up to 10 characters.
string_copy(short_string, "Hello", 11);
cout << short_string << "STRING ENDS HERE.\n";
char long_string[ ] = "This is rather long.";
string_copy(short_string, long_string, 11);
cout << short_string << "STRING ENDS HERE.\n";
return 0;
}
//Uses cstring:
void string_copy(char target[ ], const char source[ ], int target_size)
{
int new_length = strlen(source);
if (new_length > (target_size - 1))
new_length = target_size - 1; //That is all that will fit.
for (int index = 0; index < new_length; index++)
target[index] = source[index];
target[index] = '\0';
}
The program output is:
HelloSTRING ENDS HERE
This is raSTRING ENDS HERE