I want to convert a char array[] like:
char myarray[4] = {'-','1','2','3'}; //where the - means it is negative
So it should be the integer: -1234
using standard libaries in C. I could not find any elegant way to do that.
I can append the ‘\0’ for sure.
I personally don’t like
atoifunction. I would suggestsscanf:It’s very standard, it’s in the
stdio.hlibrary 🙂And in my opinion, it allows you much more freedom than
atoi, arbitrary formatting of your number-string, and probably also allows for non-number characters at the end.EDIT
I just found this wonderful question here on the site that explains and compares 3 different ways to do it –
atoi,sscanfandstrtol. Also, there is a nice more-detailed insight intosscanf(actually, the whole family of*scanffunctions).EDIT2
Looks like it’s not just me personally disliking the
atoifunction. Here’s a link to an answer explaining that theatoifunction is deprecated and should not be used in newer code.