Created
August 28, 2022 16:00
-
-
Save wisentini/3f469a393451f81c96e8df3e3b30a286 to your computer and use it in GitHub Desktop.
Convert a string to an integer in C.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <errno.h> | |
int str_to_int(char *str) | |
{ | |
int base = 10; | |
char *end_ptr; | |
errno = 0; | |
int value = (int)strtol(str, &end_ptr, base); | |
if (errno != 0 || str == end_ptr) { | |
fprintf(stderr, "\nERROR: Couldn't convert \"%s\" to an integer.\n\n", str); | |
exit(EXIT_FAILURE); | |
} | |
return value; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment