سؤال

I've written this small program to work out the check digit of a barcode. Basically it's meant to take the first digit, then 2 sets of 5 digits and do some basic arithmetic on them. When inputting the first group of 5 digits, I try to enter them all on one line, like this:

>Enter the first group of 5 digits: 12345

But it's only counting the 1 and discarding the rest of the numbers. Meaning to get the program to give the correct output I have to input the data like this:

>Enter the first group of 5 digits: 1
>2
>3
>4
>5

And only then does it prompt me for the second set of 5 digits. I've tried a number of different things, such as putting spaces between the specifier in the scanf() function but it didn't work.

Does anyone have any solutions so that I will be able to enter all 5 digits on the same line of input?

Code:

#include <stdio.h>

int main(void)
{
    int d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, first_sum, second_sum, chk_dig;

    printf("Enter the first (single) digit: ");
    scanf("%d", &d1);

    printf("\nEnter the first group of 5 digits: ");
    scanf("%d%d%d%d%d", &d2, &d3, &d4, &d5, &d6);

    printf("\nEnter the second group of 5 digits: ");
    scanf("%d%d%d%d%d", &d7, &d8, &d9, &d10, &d11);

    first_sum = d1 + d3 + d5 + d7 + d9 + d11;
    second_sum = d2 + d4 + d6 + d8 + d10;

    chk_dig = 3 * first_sum + second_sum;

    printf("\nCheck digit: %d", 9 - ((chk_dig - 1) % 10));

    return 0;
}

Thanks!

هل كانت مفيدة؟

المحلول

If you want to scan 5 separate 1-digit numbers that are adjacent to each other, tell scanf() you want 1-digit numbers:

if (scanf("%1d%1d%1d%1d%1d", &d2, &d3, &d4, &d5, &d6) != 5)
    …some sort of format error, or EOF perhaps…

That will work OK on both the inputs:

1 2 3 4 5
12345

نصائح أخرى

You can use spaces to separate numbers instead of new lines.

1 2 3 4 5

If you cram your numbers together, 12345, how is your program supposed to know you don't mean the actual number 12,345?

You should read the documentation on how scanf() works.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top