Skip to content

How to Convert a String to an Integer in C

If you need to convert a String to an Integer in C, then you can do one of the following:

Option 1 – Use atoi()

int atoi(const char *str);

You can do something like this:

#include <stdio.h> #include <stdlib.h> #include <string.h> int main (void) { int value; char str[20]; strcpy(str,"123"); value = atoi(str); printf("String value = %s, Int value = %d\n", str, value); return(); }
Code language: C++ (cpp)

Option 2 – Use strtol()

long int strtol(const char *string, char **laststr,int basenumber);

You can do something like this:

#include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { char str[10]; char *ptr; long value; strcpy(str, " 123"); value = strtol(str, &ptr, 10); printf("decimal %ld\n", value); return ; }
Code language: C++ (cpp)

Option 3 – Use strtoumax()

uintmax_t strtoumax(const char* string, char** last, int basenumber);

You can do something like this:

#include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { char str[10]; char *ptr; int value; strcpy(str, " 123"); printf("The integer value:%d",strtoumax(str, &ptr,10)); return ; }
Code language: C++ (cpp)

See also  Will there be Enough Space in Java
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x