Conversion from char type to int type in #c language (any number of digits is acceptable)

Background

When I learned c language because I needed it at school, I couldn't get it even if I googled to convert from char to int, so I wrote a memo.

Method

atoi(String);

Example

char str[]="1234";
printf("str*10=%d",atoi(str)*10); 

Execution result:

str*10=12340

A little impression

When I searched, "-'0'" came up first, but not so much about atoi. I'm new to c language so I don't know the details, but I wonder if there is a reason why it is better not to use atoi. ..

Postscript

I found it better not to use atoi. (Thanks to everyone who commented) It seems that atoi cannot detect overflow and underflow. Instead, it seems that strtol is a function that can be detected, so I will write it.

Method (Since it is converted to long type, if you want to make it int type, please cast it individually)

strtol(String,Position where conversion ended,radix);

Example

char str[]="1234";
printf("str*10=%d",strtol(str,NULL,10)*10);

Execution result:

str*10=12340

Recommended Posts