/* Programming 111 Program 04 (BookCode Validator) Coded by Blake Imsland -- This program; given a string or book code; will check the validity of said code and inform the user of any errors. -- File: program04.cpp Date: 2006/11/18 */ /* include required headers */ #include #include using namespace std; /* define constants */ #define NOS 10 // length for short code #define NOD 3 // number of dashes in long code /* prototype functions */ void directions(); bool validate(string &); /* main program */ int main() { /* prototype variables */ string bookCode; /* print directions */ directions(); /* main program loop */ while (1) { /* get code from user */ cout << "\nCode entry: "; cin >> bookCode; /* check for quit */ if (bookCode == "q" || bookCode == "Q") { break; } /* validate code */ if (validate(bookCode)) { cout << "Valid code entered;\n"; } } /* quit */ return 0; } /* print directions for user */ void directions() { cout << "Welcome to the Graysville library catalog!\n" << "Enter a book code of length 13 (with dashes) or 10 (without dashes).\n" << "The program will check the validity of the code before querying the catalog.\n"; } /* takes a string/code and checks the validity */ /* returns true if code is valid, false if not */ bool validate(string &bookCode) { /* prototype variables */ int i; bool valid = true; /* convert string to char array */ int c[bookCode.length()]; for (i=0;i '9') { cout << "Invalid digit at position " << i+1 << ";\n"; valid = false; } } /* check last digit */ if ((c[length-1] < '0' || c[length-1] > '9') && c[length-1] != 'X') { cout << "Invalid digit at position " << NOS << ";\n"; valid = false; } } /* if code is long */ else if (length == (NOS + NOD)) { /* null dash count to 0 */ int dashes = 0; /* check first digit */ if (c[0] < '0' || c[0] > '9') { if (c[0] == '-') { cout << "Invalid dash at position 1;\n"; dashes++; valid = false; } else { cout << "Invalid digit at position 1;\n"; valid = false; } } /* check whether middle digits are valid */ for (i=1;i0 && c[i-1] == '-')) { cout << "Invalid sequential dash at position " << i+1 << ";\n"; valid = false; } dashes++; } else if (c[i] < '0' || c[i] > '9') { cout << "Invalid digit at position " << i+1 << ";\n"; valid = false; } } /* check last digit */ if ((c[length-1] < '0' || c[length-1] > '9') && c[length-1] != 'X') { if (c[length-1] == '-') { cout << "Invalid dash at position " << length << ";\n"; dashes++; valid = false; } else { cout << "Invalid digit at position " << length << ";\n"; valid = false; } } /* check dash count */ if (dashes != NOD) { cout << "Invalid number of dashes " << dashes << ";\n"; valid = false; } } /* if code is neither */ else { cout << "Invalid code length of " << length << ";\n"; valid = false; } return valid; }