Skip to content

Instantly share code, notes, and snippets.

@gustavorv86
Last active August 13, 2019 11:10
Show Gist options
  • Save gustavorv86/1e7672a4d127bd5edf46f7c9aa4d4a6b to your computer and use it in GitHub Desktop.
Save gustavorv86/1e7672a4d127bd5edf46f7c9aa4d4a6b to your computer and use it in GitHub Desktop.
Converts string to integer checking input errors.
/**
* Compile:
* gcc -Wall -Wextra -ggdb c_string_to_int.c -o string_to_int
*/
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
int string_to_int(const char * string, int * retval) {
int tmpval = 0;
char * endptr = NULL;
errno = 0; // Include errno.h
tmpval = strtol(string, &endptr, 10);
if(string == endptr) {
return -1;
} else if(*endptr != '\0') {
return -2;
} else if(errno != 0) {
return -3;
} else {
*retval = tmpval;
return 0;
}
}
int main(int argc, char ** argv) {
if(argc < 2) {
fprintf(stderr, "Usage: %s str\n", argv[0]);
exit(1);
}
const char * string = argv[1];
int value;
int status = string_to_int(string, &value);
if(status == 0) {
printf("INTEGER VALUE: %d\n", value);
} else {
printf("CANNOT CONVERT \"%s\" TO INTEGER VALUE, RETURN CODE: %d\n", string, status);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment