I am at the moment trying to grasp multi-file programming instead of one big main.cpp.
The class I wrote is about ISBN 13.
Can you point out what could be done to improve my code?
Also is there a good guide how to write include guards? My sources differate in this respect.
ISBN.hpp
#include <ostream>
class ISBN
{
/* examples 978-345-314-697-6
978-3-12-732320-7
*/
private:
//the numbers between the minus signs
unsigned int isbn_field1;
unsigned int isbn_field2;
unsigned int isbn_field3;
unsigned int isbn_field4;
unsigned int isbn_field5;
public:
//constructors
ISBN()
: ISBN{978,3,12,732320,7} // a valid ISBN as default
{}
ISBN(const unsigned int& a, const unsigned int& b, const unsigned int& c, const unsigned int& d, const unsigned int& e);
//output operator overloading
friend std::ostream& operator<<(std::ostream& os, ISBN const& i);
};//ISBN
ISBN.cpp
#include "ISBN.hpp"
#include <iostream>
#include <string>
bool is_valid_isbn(const std::string& digits)
{
unsigned int weighted_sum=0;
std::string temp;
for (unsigned int i=0; i<(digits.length());i++)
{
temp=digits[i];
if ((i%2)==0)
{
weighted_sum+=std::stoi(temp);
}
else
{
weighted_sum+=std::stoi(temp)*3;
}
}
if ((weighted_sum%10)!=0)
{
return false;
}
return true;
}
ISBN::ISBN(const unsigned int& a, const unsigned int& b, const unsigned int& c, const unsigned int& d, const unsigned int& e)
{
const std::string digit_string=std::to_string(a)
+std::to_string(b)
+std::to_string(c)
+std::to_string(d)
+std::to_string(e);
std::string temp;
//check if last field is exactly one digit
temp=std::to_string(e);
if(temp.length()!=1)
{
throw "last unit is not a single digit\n";
}
//check if first field is 978 or 979
if(a!=978 && a!=979)
{
throw "first unit is neither 978 nor 979\n";
}
//check number of digits=13
if(digit_string.length()!=13)
{
throw "number of digits is not exactly 13\n";
}
if (!is_valid_isbn(digit_string))
{
throw "not a valid ISBN\n";
}
isbn_field1=a;
isbn_field2=b;
isbn_field3=c;
isbn_field4=d;
isbn_field5=e;
}
std::ostream& operator<<(std::ostream& os, ISBN const& i)
{
return os << i.isbn_field1 << "-"
<< i.isbn_field2 << "-"
<< i.isbn_field3 << "-"
<< i.isbn_field4 << "-"
<< i.isbn_field5;
}
main.cpp
#include "ISBN.hpp"
#include <iostream>
int main()
{
try
{
ISBN test;
std::cout << test;
}
catch(char const* e)
{
std::cout << "Error:" << e;
}
catch(...)
{
std::cout << "test error";
}
return 0;
}