简体   繁体   English

C 将 char* 字符串转换为 int 数组

[英]C Convert char* string to int array

I have a char* string of only exactly 5 digits.我有一个只有 5 位数字的char*字符串。 I want to convert this string to a integer array.我想将此字符串转换为 integer 数组。

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: 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)?为什么数字显示不正确(0、0、4、1、1)?

What you are getting is the ASCII equivalent characters.您得到的是 ASCII 等效字符。 Subtract '0' to get the original number from ASCII characters.减去'0'以从 ASCII 字符中获取原始数字。
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]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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