Search code examples
c++arraysvisual-c++isbn

Simple C++ Array Logic Issue


I'm attempting to write a program in which the user enters an ISBN then checks the entry for accuracy. The ISBN is 0201702894. The check digit (the 4) is calculated from the other 9 digits as follows – the (sum of each (digit times its position)) mod 11. Ex: (0*1 + 2*2 + 0*3 + 1*4 + 7*5 + 0*6 + 2*7 + 8*8 + 9*9)%11 = (0+4+0+4+35+0+14+64+81)%11 = 4 (202/11 = 18 remainder 4) The check digit can detect when an ISBN is entered or copied incorrectly.

Each time I enter values, I always have the "ISBN is not correct" output. Something is wrong with my logic.

1.  Correct Value: 0201702894

2.  Incorrect value: 0201702984

Code:

#include <iostream>

using namespace std;

int totalNumbersCheck=0;

int main()
{
int isbnArray[10];      //array to store the ISBN numbers
int ISBN=0;             //inputted ISBN number

//user input

cout<<"Please enter the ISBN number: ";
cin>>ISBN;

//ISBN storage

isbnArray[ISBN];

//ISBN calculation

for(int i=0;i<10;i++)
{
    totalNumbersCheck=isbnArray[i]*(i+1);
}

//remove last element from array

    totalNumbersCheck-=isbnArray[10];

//check if remainder equals last element and output correct response

    if(totalNumbersCheck%11==isbnArray[10])
    {
        cout<<"\nThe ISBN is correct.";
    }
    else
        cout<<"\nThe ISBN is not correct.";

    cin.get();
    cin.get();

return 0;
  }

Solution

  • Read the isbn into a std::string variable, then loop through the characters in the string, convert each to a digit, and apply your algorithm.

    const isbn_digits = 10;
    std::string isbn;
    std::cin >> isbn;
    assert(isbn.size() == isbn_digits);
    int sum = 0;
    for (int pos = 0; pos < isbn_digits - 1; ++pos)
        sum += (pos + 1) * (isbn[pos] - '0');
    if (sum % 11 != isbn[isbn_digits - 1] - '0')
        // error