First, here is a writeup on C strings, i.e., strings as represented in C (and often used as the underlying structure for
the C++ string
class).
In the Standard C Library there is a library (i.e., header) named cstring
, containing a collection of functions used to manipulate C-Strings.
In this exercise, you are to implement several of the functions provided by the cstring
library. Since we are 'hijacking' the C-String library, there is
concern about name clashing — we will use a namespace to avoid that — see below. (In actuality, the clashes don't really arise until the upcoming related lab that has you define
a simple string class; but we'll get started with the namespace now, while things are simple.)
Implement a cstring
module (with a .h
/.cpp
pair) containing the following C-style (i.e., non-member) functions:
char *strcpy(char *dest, const char *src); char *strcat(char *dest, const char *src); int strcmp(const char *str1, const char *str2); char *strchr(char *str, int c); char *strrchr(char *str, int c); int strlen(const char *str);the module should belong to the namespace
mystring
(see below).
(If you really want some fun, try coding a couple of the above recursively — strlen
is
a good place to start).
I've provided a cstring_app.cpp
test driver.
mystring
. The contents
of a namespace may be distributed across multiple files — source as well as header. The basic syntax for placing code within a namespace is:
namespace <namespace-name { … // code belonging to the namespace … }Pragmatically speaking, in a header (
.h
) file, place this between the include guards (i.e., have the include guards be the outermost
code of the file, then enclose everything else, e.g., the class declaration, within the namespace body. For a source file, have all the includes and
using appear before the namespace, and the rest of the file (i.e., your actual code) be enclosed within the namespace body as well.
std
and mystring
(there's actually a third you've been using, the
global namespace). Recall that when using an entity (type, object, function, etc) from a namespace you must provide additional
information to help the compiler find the entity. This can be done by either:
std::cout
or mystring::strcmp
using namespace mystring
; this allows the entire contents of the
specified namespace to be used without requiring the scope resolution operator.
using std::cout
; this brings the specified entity into the current scope
and allows it to be used without requiring the scope resolution operator.
string
class later on