#ifndef FIXEDSTRING_H // see page 96 for explanation
#define FIXEDSTRING_H
#include <iostream.h>
#include <iomanip.h>
const int MaxSize = 256; // Maximum allowable string size
class FixedString {
friend bool operator <(const FixedString & s1,
const FixedString & s2);
friend istream & operator >>( istream & inp,
FixedString & s );
friend ostream & operator <<( ostream & inp,
const FixedString & s );
public:
FixedString();
FixedString( const char * s );
FixedString( const FixedString & s );
private:
char str[MaxSize+1]; // String characters
};
#endif
// FIXEDSTRING.CPP - FixedString member function definitions
// Fixed-length string class: allocate 256 characters for every string
// Makes strings first class objects: Version 1
// Construct from C-style strings
// or by Copying another FixedString Object
// Overload I/O operators
#include "fixedString.h"
#include <string.h> // build on C-style strings
//######### define friends first
bool operator <(const FixedString & s1,
const FixedString & s2)
{
if(strcmp(s1.str,s2.str) < 0)
return true;
else
return false;
}
istream & operator >>( istream & inp, FixedString & s )
{
inp.get(s.str,MaxSize+1,'\n');
inp.ignore(1000,'\n'); // skip to end of line
return inp;
}
ostream & operator <<( ostream & outp, const FixedString & s )
{
outp << s.str;
return outp;
}
//####### define member functions
FixedString::FixedString()
{
str[0] = '\0';
}
FixedString::FixedString( const char * s )
{
strncpy(str,s,MaxSize);
str[MaxSize] = '\0'; // in case "s" is too big
}
FixedString::FixedString( const FixedString & s )
{
strncpy(str, s.str, MaxSize);
str[MaxSize] = '\0'; // in case "s" is too big
//- should never happen but who knows?
}
- change so fixed strings are only 100 characters long
- could you change the size of strings without recompiling
the implementation file "FixedString.cpp"
- could you write the overloaded comparison operators so
they are not friends? explain
- give the prototype for a selector member function which
will return the C-style string that is a copy of the
value stored in the object
- what are the precondition/postconditions for this
function?
- Would this class compile and operate successfully if the
"const" modifier was removed from the two
FixedString non-default constructors.
- the private data member can hold a string up to 256
characters long. How can you tell the length of a
FixedString Object? Add a second data member called
"length" which keeps the length of the String.
modify the appropraite member functions to keep this
length attribute consistent
- If we added a length attribute, would we need to insert a
null character '\0' at the end of the string?
- what is type of str[MaxSize] (in the constructors)? what
is the type of str? what is the type of MaxSize?
- write the postcondition for the default constructor
- in the second non-default constructor why is the strncpy
using arguments "str" and "s.str"
what is "str" and "s.str"?
- where is strncopy defined?