A check digit (aka checksum digit) is added to a number, such as book ISBN numbe
ID: 3691723 • Letter: A
Question
A check digit (aka checksum digit) is added to a number, such as book ISBN number or bank routing number, to verify the correctness of the number. The check digit is usually added as the last digit in the number. A common usage of a check digit is to detect errors made while entering the number into a system. For this assignment, you will write a C++ program to generate check digits for ISBN-13 numbers.
The ISBN-13 is a standard, introduced in 2007, for identifying books. It uses 13 digits d0d1d2d3d4d5d6d7d8d9d10d11d12. The last digit d12 (i.e., the 13th digit) is check digit that is calculated from the other digits using the following formula:
10 - (d0 + d1 * 3 + d2 + d3 * 3 + d4 + d5 * 3 + d6 + d7 * 3 + d8 + d9 * 3 + d10 + d11 * 3) % 10
If the checksum is 10, replace it with 0.
Your code must have a function that accepts a string parameter of the first 12-digits in an ISBN-13 number and returns the checksum digit (i.e., the 13th digit). You may use other functions if you like. For example, a helpful function takes a character containing a digit as parameter and returns that digit as an integer, which you can define as follows:
The program must read input from a file, named isbn.txt, that is located in the same folder as the program. Each line on the file contains the first 12-digits of a valid ISBN-13 number. The program outputs to the computer's screen the checksum digit for each number in the file. For example, using the following input file:
your program should produce the following output:
Explanation / Answer
#include<iostream>
#include <fstream>
#include <sstream>
using namespace std;
int checksum(string s){
istringstream iss(s);
long n;
int check_digit=0;
iss>>n;
while(n>0){
check_digit =check_digit + (n%10) * 3;
n = n/10;
check_digit = check_digit + (n%10);
n = n/10;
}
check_digit = 10 - (check_digit %10);
check_digit = check_digit % 10;
return check_digit;
}
int main(){
ifstream infile;
infile.open ("isbn.txt");
string s;
while(infile>>s)
cout<<checksum(s)<<endl;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.