how do I assign the values in array elements text[3] and text[4] to int so int will equal 45?Code:int x
char text[10] = {"123456789"};
Printable View
how do I assign the values in array elements text[3] and text[4] to int so int will equal 45?Code:int x
char text[10] = {"123456789"};
Code:/* silly way, converting each element to an integer */
x = (text[3]-'0') * 10 + (text[4]-'0');
/* slightly less silly way */
char new[16] = { 0 };
strncpy(new, text + 3, 2); /* copy text[3] and text[4] to new */
new[2] = '\0'; /* null terminate new */
x = atoi(new); /* or use strtol for error checking */
Another simple way. Not very efficient when you want to do several characters.
Code:int x
char text[10] = {"123456789"};
x = text[3] - '0' + text[4] - '0';
Ancient Dragon, that's the way I suggested above, except I multiplied the first term by 10. Your way just adds them, producing 9, not 45.