-2

I have a char* string of only exactly 5 digits. I want to convert this string to a integer array.

I've tried this:

#include <stdio.h>
#include <string.h>

int main()
{
     int numbers[5];
     const char* titleid = "TEST00411";
     const char* digits = titleid + 4;
     
     for (int i = 0; i < 5; ++i) {
          numbers[i] = digits[i];
          printf("LOOP: %d\n", digits[i]);
     }
     
     printf("%d\n", numbers[0]);
     printf("%d\n", numbers[1]);
     printf("%d\n", numbers[2]);
     printf("%d\n", numbers[3]);
     printf("%d\n", numbers[4]);
     
     return 0;
}

Output:

LOOP: 48
LOOP: 48
LOOP: 52
LOOP: 49
LOOP: 49
48
48
52
49
49

Why aren't the numbers displayed correctly (0, 0, 4, 1, 1)?

Appel Flap
  • 261
  • 3
  • 23
  • 4
    Hint: The ASCII for `'0'` is `48`, `'1'` is `49`, etc. – Dai Aug 07 '20 at 13:12
  • 2
    **This does not do what you think it does**: `numbers[i] = digits[i];` – Dai Aug 07 '20 at 13:12
  • 1
    The C specification requires that all digit characters are encoded in a contiguous way. The character encoding for `1` (i.e. `'1'`) will always come after the character encoding for `0'` (i.e. `'0'`). That is, `'0' < '1'` will always be true, and the difference `'1' - '0'` will always be `1`. It shouldn't take very long using pen and paper to figure out how you can convert from the character encoding to the integer value for that digit. Or you just do some searching as this is *very* well-known and documented everywhere. A decent book, tutorial or class might even include that information. – Some programmer dude Aug 07 '20 at 13:18
  • @Appel Flap Just use the format specifier %c instead of ^d printf("%c\n", numbers[0]); :) – Vlad from Moscow Aug 07 '20 at 13:32

1 Answers1

2

What you are getting is the ASCII equivalent characters. Subtract '0' to get the original number from ASCII characters.
Here is the code to just do it.

for (int i = 0; i < 5; ++i) {
          numbers[i] = digits[i]-'0';
          printf("LOOP: %d\n", digits[i]);
}
Sourabh Choure
  • 723
  • 4
  • 15