#include "apvector.h" #include "apstring.h" #include #include template class apvector; const int MINLEN = 5; const int MAXLEN = 15; class Code { public: Code(); // length is 0, capacity is MAXLEN chars Code(const apstring & s); // code has chars in s, length is s.length() bool IsValid(); // returns true if code is valid, else false int Length(); // returns # characters in the code void AppendCheckSum(); // adds appropriate check sum // other functions not shown void print(ostream & os) const; private: int myLength; // # characters in code apvector myChars; // the characters in the code }; ostream& operator << (ostream& os, const Code & s) { s.print(os); return os; } int digitToInt(char d) // precondition: isdigit(d) == true // postcondition: returns the value 0 to 9 corresponding // to character d { return d - '0'; } char intToDigit(int val) // precondition: 0 <= val <= 9 // postcondition: returns the character from // '0'..'9' corresponding to val { return '0' + val; } Code::Code() : myLength(0), myChars(MAXLEN) { } Code::Code(const apstring & s) : myLength(s.length()), myChars(MAXLEN) { int k; for(k=0; k < myLength; k++) { myChars[k] = s[k]; } } bool Code::IsValid() // postcondition: returns true if MINLEN <= Length() < MAXLEN - 2 // and for every k, 0 <= k < Length(), // myChars[k] is a digit '0'--'9' or a char 'A' -- 'Z' { if (Length() < MINLEN || MAXLEN - 2 < Length()) { return false; } int k; for(k=0; k < Length(); k++) { if (! isupper(myChars[k]) && ! isdigit(myChars[k])) return false; } return true; } void Code::AppendCheckSum() // postcondition: if IsValid() then myLength is updated and // myChars contains the original characters followed // by a dash and the appropriate checksum; otherwise // myLength and myChars are unchanged { if (IsValid()) { int k; int sum = 0; int len = Length(); // could use myLength here too for(k=0; k < len; k++) { if (isdigit(myChars[k])) { sum += digitToInt(myChars[k]); } } myChars[myLength] = '-'; myChars[myLength+1] = intToDigit(sum % 10); myLength += 2; } } int Code::Length() { return myLength; } void Code::print(ostream & os) const { int k; for(k=0; k < myLength; k++) { os << myChars[k]; } } void doCode(Code c) { cout << c; if (c.IsValid()) { c.AppendCheckSum(); cout << " is valid with check sum = " << c << endl; } else { cout << " is NOT valid" << endl; } } int main() { Code a("ABCDE9999"); Code b("ab?XX123"); doCode(a); doCode(b); }