I am trying to find out if there is an alternative way of converting string to integer in C.
I regularly pattern the following in my code.
char s[] = "45";
int num = atoi(s);
So, is there a better way or another way?
I am trying to find out if there is an alternative way of converting string to integer in C.
I regularly pattern the following in my code.
char s[] = "45";
int num = atoi(s);
So, is there a better way or another way?
You can always roll your own!
This will do what you want without clutter.
You can code a little atoi() for fun:
You can also make it recursive wich can old in 3 lines =)
Ok, I had the same problem.I came up with this solution.It worked for me the best.I did try atoi() but didn't work well for me.So here is my solution:
Just wanted to share a solution for unsigned long aswell.
Don't use functions from
ato...
group. These are broken and virtually useless. A moderately better solution would be to usesscanf
, although it is not perfect either.To convert string to integer, functions from
strto...
group should be used. In your specific case it would bestrtol
function.In C++, you can use a such function:
This can help you to convert any string to any type such as float, int, double...