I am writing code in C++ for a class project. I am writing a program that checks the first 12 digits of an ISBN-13 number. Given 12 numbers it will calculate and display the full 13 digit ISBN. My biggest problem is that I cannot figure out how to convert my string of digits entered by the user into an integer in such a way that I can use each digit to perform the calculation. Any help would be greatly appreciated! Here is the portion of code that I need to have integers to perform the calculation. The isbn[d] seen below is what I need to convert to an integer and then use each single integer value. That variable is a string which the user enters.
//Sum the digits alternating multiples of 1 and 3, 12 times
for (unsignedint d = 0; d < 12; d++) {
dProduct = isbn[d];
cout << dProduct << endl;
if (d % 2 == 0) {
sum += dProduct * 1;
} else {
sum += dProduct * 3;
}
}
newSum = 10 - (sum % 10);
if (newSum == 10) {
cout << "The ISBN-13 number is " << isbn << "0" << endl;
} else {
cout << "The ISBN-13 number is " << isbn << newSum << endl;
}
}
Awesome! I will give that a shot. I also thought about converting from ascii back to the numbers they were as a string within the loop. I guess that would work also?
To convert the integer back into a string? Sure, that can be done as well.
You mentioned ASCII, so maybe you're already familiar with ASCII, so check here: http://www.asciitable.com/
for the actual values stored in memory. You can add/subtract characters/numbers to convert based on the values in that ascii table.
Like when I did int i = s[2] - '0's[2] is the character '3', but its ascii value is 51. The ascii value for '0' is 48, so subtracting the two (s[2] - '0') gives us 3, which is exactly what we wanted. We can just store that in an integer variable instead of a character variable.
To go back just add '0' instead of subtracting and you'll get the ascii value for whatever integer it was before you converted. Just be sure to store it in a character variable instead of an integer variable or it'll print as an integer instead of a character.