I need to read in a 13 digit number which is barcode, and then I need to spit it out with hyphens added after the 3rd, 9th and 12th digit.
So if the user inputs barcode 1234567890123 then my program should output 123-456789-012-3
I'm learning how to code in a class and so we are restricted with what functions and whatnot we can use, so please bare with me.
What I have so far:
Code:
#include <stdio.h>
#include <assert.h>
#define UPPER_LIMIT 10000000000000LL
#define LOWER_LIMIT 1000000000000LL
#define FIRST_HYPHEN 10000000000LL
#define SECOND_HYPHEN 10000
#define THIRD_HYPHEN 10
int main(int argc, char *argv[]) {
long long barcode = 0;
int numScanned = -1;
long long remainder = 0;
printf("Enter your barcode: ");
numScanned = scanf("%lld", &barcode);
//Check that assumptions have been followed
assert( (numScanned == 1) && ((barcode / LOWER_LIMIT) != 0) );
remainder = barcode;
long long i = LOWER_LIMIT;
//Loop to get digits of barcode
for (i = LOWER_LIMIT; i > 0; i = i / 10) {
if ( (remainder / FIRST_HYPHEN == 0)
|| (remainder / SECOND_HYPHEN == 0)
|| (remainder / THIRD_HYPHEN == 0) ) {
printf("-");
} else {
printf("%lld", remainder / i );
}
remainder = remainder % i;
}
printf("\n");
return 0;
}
And it took me a while to figure out why with input 1234567890123 I'm receiving output 123-----------, but I realized it's because in my loop near the end,
Code:
if ( (remainder / FIRST_HYPHEN == 0)
|| (remainder / SECOND_HYPHEN == 0)
|| (remainder / THIRD_HYPHEN == 0) ) {
printf("-");
} else {
printf("%lld", remainder / i );
}
This if statement means that it prints a hyphen after the 3rd digit as expected, but after that, the remainder is 1 digit less, but remainder / FIRST_HYPHEN == 0 is still true. What I intended for that if loop to do was to only be true if the remainder was 10 digits, 4 digits and 1 digit long. Any suggestions as to how I can work around this?