简体   繁体   中英

C Convert char* string to int array

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)?

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]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM