2

I'm inputting an 11 digit UPC code, and trying to split the digits up to handle them separately. I can't figure out why I'm getting one input correctly parsed and the other one with completely random values.

Code:

int input, n1, n2, n3, n4, n5, n6, n7, n8, n9, n10, n11, check_digit;

printf("Enter the UPC Code: ");
scanf("%d", &input);

n11 = input % 10;
input /= 10;
n10 = input % 10;
input /= 10;
n9 = input % 10;
input /= 10;
n8 = input % 10;
input /= 10;
n7 = input % 10;
input /= 10;
n6 = input % 10; 
input /= 10;
n5 = input % 10;
input /= 10;
n4 = input % 10;
input /= 10;
n3 = input % 10;
input /= 10;
n2 = input % 10;
input /= 10;
n1 = input % 10;

printf("%d%d%d%d%d%d%d%d%d%d%d\n\n", n1, n2, n3, n4, n5, n6, n7, n8, n9, n10, n11);

return 0;

What I get in return when inputting the second value is completely random negative numbers. Can anyone figure out what I'm doing wrong?

:Chapter_4$ ./PP4.5 Enter the UPC Code: 01234567891

01234567891

:Chapter_4$ ./PP4.5 Enter the UPC Code: 37482637462

0-1-1-7-20-6-8-20-2

1 Answers1

2

It appears that 37482637462 is larger than what an int can hold on your platform. Due to integer overflow, you end up with a negative number.

You can try an unsigned int to work with it, if an unsigned int can hold that number on your platform. If not, you will get undefined behavior.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • 1
    I concur with this answer, Further, if `int` can't hold that, it means your `int` is likely 32bit (or shorter), which means your `unsigned int` is likewise so. Time to break out either a `unsigned long long` or better still, take out the guesswork and just use `` and `uint64_t` (and note, the `printf` format specifier, `PRIu64`, takes a little getting used to using. [See this](http://stackoverflow.com/questions/8132399/how-to-printf-uint64-t)). Or, of course, bignum-lib it. – WhozCraig Jun 14 '14 at 04:38