-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2_5_ISBN_validator.cpp
118 lines (103 loc) · 2.78 KB
/
2_5_ISBN_validator.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#include <iostream>
using std::cin;
using std::cout;
/*
ISBN validator without using arrays.
*/
/* (AD): Define a new type for enum (T_ISBNPART_ENUM) and name enums as T_ISBNPART_PREFIX, T_ISBNPART_GROUP... */
enum isbnPart {PREFIX, GROUP, REGISTRANT, PUBLICATION, CHECK, COMPLETED};
bool verifyPart(int nr, int digitCount, int part);
bool verifyCheckDigit(int nr);
int main()
{
char digitChar;
char ch = '0';
int nr = 0;
int digit = 0;
int modulo = 0;
int part = PREFIX;
int digitCount = 0;
int totalDigitCount = 0;
int checkSum = 0;
int pos = 1;
bool invalidNr = false;
cout << "Type in ISBN number. 13 digits to validate, 12 digits to get the checksum digit:\n";
do {
ch = cin.get();
digitCount++;
if(ch == '-' || ch == 10)
{
if (!verifyPart(nr, digitCount, part))
{
invalidNr = true;
break;
}
part = ++part % 6;
digitCount = nr = 0;
} else {
nr = nr*10 + (ch - '0');
digit = ch - '0';
totalDigitCount++;
checkSum += (pos % 2 == 0) ? digit * 3: digit;
pos++;
}
} while(ch != 10);
// Check if the number is too long
if (!(part == CHECK && totalDigitCount==12) && !(part == COMPLETED && totalDigitCount==13))
{
invalidNr = true;
}
// Check if the number is valid in its format
if (invalidNr || part < CHECK || part > COMPLETED)
{
cout << "The number is not valid!\n";
} // Then get the checksum digit
else if (part == CHECK)
{
int checkDigit = 10 - checkSum % 10;
cout << "The check digit is " << checkDigit << " \n";
} // Else check the checksum
else if (part == COMPLETED)
{
if (checkSum % 10 == 0)
{
cout << "The ISBN is valid\n";
} else {
cout << "The ISBN is not valid\n";
}
}
else
{
cout << "Something went wrong!\n";
}
cin.get();
return 0;
}
bool verifyPart(int nr, int digitCount, int part)
{
bool isVerified = false;
switch(part)
{
case PREFIX:
isVerified = (nr == 978 || nr == 979);
break;
case GROUP:
isVerified = (digitCount >= 1 && digitCount <= 5);
break;
case REGISTRANT:
isVerified = (digitCount >= 1 && digitCount <= 6);
break;
case PUBLICATION:
isVerified = (digitCount >= 1 && digitCount <= 7);
break;
case CHECK:
isVerified = (nr < 10 || nr >= 0);
break;
case COMPLETED:
isVerified = false;
break;
default:
isVerified = false;
}
return isVerified;
}