How would I go about converting a two-digit number (type char*
) to an int
?
Asked
Active
Viewed 1.9e+01k times
52

Stefan van den Akker
- 6,661
- 7
- 48
- 63

Niek
- 1,000
- 2
- 9
- 19
-
1http://www.cplusplus.com/reference/clibrary/cstdlib/strtol/ – Marc B Oct 30 '12 at 18:54
-
1Accept aam1r's answer if it was the solution please. – Goz Oct 30 '12 at 21:02
2 Answers
11
Use atoi() from <stdlib.h>
http://linux.die.net/man/3/atoi
Or, write your own atoi()
function which will convert char*
to int
int a2i(const char *s)
{
int sign=1;
if(*s == '-'){
sign = -1;
s++;
}
int num=0;
while(*s){
num=((*s)-'0')+num*10;
s++;
}
return num*sign;
}
-
a2i is perfect solution just need a fix for negative case add bracket on if will fix it if(*s == '-') { sign = -1; s++; } – Aurélien Pigot Bennour Jul 27 '15 at 20:50