0

This code removes (ignores) the "-" from a string, but only one time. How can I reset the *p to let it do the loop again, after I changed my ISBN string?

char ISBN[] = "3-423-62167-2";
char *p = ISBN;
while (*p)
{
    if (isdigit(*p))
    {
        const char digit = *p - '0';
        num = (num * 10) + digit;
    }
    ++p;
}

//New char ISBN[] = "3-446-19313-8" and start from beginning
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Tommy
  • 15
  • 4
  • http://stackoverflow.com/q/9895216 – Robert Harvey Jan 22 '14 at 01:27
  • Wrap the code as a function: `int strtoisbn(char const *str) { int isbn = 0; unsigned char c; while ((c = *str++) != '\0') { if (isdigit(c)) isbn = isbn * 10 + (c - '0'); } return isbn; }`. Then use it: `int isbn1 = strtoisbn("3-423-62167-2"); int isbn2 = strtoisbn("3-446-19313-8");` You may need to worry about the use of `int` as the data type (especially for 13-digit ISBNs); you might well need `long long` or `int64_t`. You may also have to worry about the `X` check digit for 10-digit ISBNs. – Jonathan Leffler Jan 22 '14 at 02:10
  • @RobertHarvey: I think your x-ref is dealing with a different problem altogether. I can see the superficial relationship, but I believe this is about reusing the code fragment to convert two ISBN numbers. – Jonathan Leffler Jan 22 '14 at 02:13
  • @JonathanLeffler: I will defer to your psychic debugger skills. – Robert Harvey Jan 22 '14 at 05:00
  • New `char ISBN[]` will be in a different memory location, assign its address to `p` then you can start from the beginning of the new memory location. – alvits Jan 22 '14 at 05:06

1 Answers1

2

Wrap the code as a function:

int strtoisbn(char const *str)
{
    int isbn = 0;
    unsigned char c;
    while ((c = *str++) != '\0')
    {
        if (isdigit(c))
            isbn = isbn * 10 + (c - '0');
    }
    return isbn;
}

Then use it:

int isbn1 = strtoisbn("3-423-62167-2");
int isbn2 = strtoisbn("3-446-19313-8");

You need to worry about the use of int as the data type (especially for 13-digit ISBNs); you might well need long long or int64_t or an unsigned variant of those. You also have to worry about the X check digit for 10-digit ISBNs; these are not a factor in 13-digit ISBNs.

If you can't write functions yet, then (a) learn how to, and (b) reinitialize p to point to the new ISBN:

p = ISBN2;

and then run the same code again. But writing the same code twice is an indication that you probably need to write a function to do the job.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278