I'm trying to write this program with helper functions that creates a barcode for a 5 digit zip code. This is using a normal 7,4,2,1,0 weighting system. Half bars are denoted by ":" and full bars are denoted by "|" and I have a "|" on either end of the code. I'm getting this exception from the stoi function I used to convert the substr (thought it would be easier to not have to reverse the separated digits as I would have to had done by separating with modulus and division). Does anyone know why?
Error Message: erminate called after throwing an instance of 'std::invalid_argument'
what(): stol
#include <iostream>
#include <string>
usingnamespace std;
/** Converts single digits to barcode fragment strings
* @param digit (number to be converted)
* @return bar (barcode fragment)
*/
string digit_to_bar(int digit)
{
string bar;
switch(digit)
{
case 0: bar = "||:::";
case 1: bar = ":::||";
case 2: bar = "::|:|";
case 3: bar = "::||:";
case 4: bar = ":|::|";
case 5: bar = ":|:|:";
case 6: bar = ":||::";
case 7: bar = "|:::|";
case 8: bar = "|::|:";
case 9: bar = "|:|::";
}
return bar;
}
/** Calculates checksum digit of 5 digit zip code
* @param input (zip code)
* @return result (number required to reach checksum)
*/
int checksum(int input)
{
int sum = 0, result = 0;
while(input > 0)
{
sum += input % 10;
input /= 10;
}
while(sum % 10 != 0)
{
result++;
sum++;
}
return result;
}
string printBarcode(int zip)
{
/** calculate checksum digit and convert to string */
string check_digit = to_string(checksum(zip));
string complete = "| ";
string digits = to_string(zip);
for(int i = 0; i <= 5; i++)
{
string current = digits.substr(i, 1);
int k = stoi(current);
string bar = digit_to_bar(k);
complete += bar;
}
complete += digit_to_bar(checksum(zip)) + " |";
return complete;
}
/** Main function
* no paramaters
* returns 0
*/
int main()
{
cout << "Enter a ZIP: ";
int d;
cin >> d;
string barcode = printBarcode(d);
cout << barcode;
return 0;
}