简体   繁体   English

将char字符串解析为INT C编程

[英]Parse a char string into an INT C programming

I'm trying to parse a char string into an INT. 我正在尝试将一个char字符串解析为一个INT。

If I had... 如果我有...

unsigned char color[] = "255"

And wanted to parse this into an INT. 并希望将其解析为一个INT。 How would I go about doing this? 我将如何去做呢?

I tried... 我试过了...

unsigned char *split;

split = strtok(color," ,.-");
while(split != NULL)
{
    split = strok(NULL, " ,.-);
}

This just gives me the value 255 for split now. 这给我现在的拆分值为255。

I feel like I need something like... 我觉得我需要...

int y = split - '0';   //but this makes an INT pointer without a cast

To convert a string to integer, call strtol : 要将字符串转换为整数,请调用strtol

char color[] = "255";
long n;
char *end = NULL;
n = strtol(color, &end, 10);
if (*end == '\0') {
    // convert was successful
    // n is the result
}

If you want to convert without calling strtol you can scan the color array and compare each char against '0' to get the corresponding numeric value, then add the result properly multiplied by a power of 10, ie 如果要在不调用strtol的情况下进行转换,则可以扫描color数组并将每个char'0'进行比较以获得相应的数值,然后将结果正确乘以10的幂,即

int i = 0, strlen = 0, result = 0;
while (color[i++]) strlen++;
for (i = 0; i<strlen; i++)
{
    result += (color[i] - '0')*pow(10,strlen-1-i);
}

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

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