new to the forum...need homework help

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21


		//Sum the digits alternating multiples of 1 and 3, 12 times
		for (unsigned int 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;
		}
	}

Last edited on
Deleted
Last edited on
Have you looked at: http://www.cplusplus.com/reference/cstdlib/atoi/ ?
It will convert a string to an integer. There are versions of this for double, float, long, and long long as well.


So keep that in mind.

Edit:
atoi can convert an entire string, but works with C-strings.
You can do this to convert your entire string to an integer
1
2
std::string s = "12345";
int i = std::atoi(s.c_str());

But that won't work for a single character indexed from that string.

You can do this to convert a character to an integer:
1
2
3
std::string s = "12345";
int i = s[2] - '0';
std::cout << "i = " << i << std::endl;


This will produce this output:
i = 3
Last edited on
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.
Topic archived. No new replies allowed.