user3622460
user3622460

Reputation: 1251

Parse a char string into an INT C programming

I'm trying to parse a char string into an INT.

If I had...

unsigned char color[] = "255"

And wanted to parse this into an 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.

I feel like I need something like...

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

Upvotes: 1

Views: 96

Answers (2)

ad3angel1s
ad3angel1s

Reputation: 500

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, i.e.

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

Upvotes: 0

fluter
fluter

Reputation: 13786

To convert a string to integer, call strtol:

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

Upvotes: 5

Related Questions