Skip to content

Instantly share code, notes, and snippets.

@wisentini
Created August 28, 2022 16:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wisentini/3f469a393451f81c96e8df3e3b30a286 to your computer and use it in GitHub Desktop.
Save wisentini/3f469a393451f81c96e8df3e3b30a286 to your computer and use it in GitHub Desktop.
Convert a string to an integer in C.
#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