Convert String to Int without any libs
Sigiloso
#include #include #include #include // Takes in a base 10 trimmed string (no whitespaces at front or back), and // returns the integer value of the string. int my_atoi(char *str, bool *valid) { int len = strlen (str), i, end, iter, ret = 0; bool neg = false; // If we got an empty string, just bail. if (len == 0) { *valid = false; return ret; } // Validate that all characters are '0' through '9', '-' is valid as the // first character for negative numbers. for (i = 0; i '9') { if (i == 0 && str[i] == '-') { // it's good neg = true; } else { *valid = false; return ret; } } } *valid = true; // When we loop backwards, is it negative or positive? end = neg ? 1 : 0; // Loop backwards through the string, get the value of the character by // subtracting '0', and multiplying by the power of 10. for (i = len - 1, iter = 1, ret = 0; i >= end; --i, iter *= 10) { ret += ((str[i] - '0') * iter); } // If it is a negative number, just multiply by -1. if (neg) { ret = ret * -1; } return ret; } void usage(char *prog) { printf ("usage: %s number\n", prog); exit(0); } int main(int argc, char** argv) { bool b; int ret; if (argc != 2) { usage (argv[0]); } ret = my_atoi (argv[1], &b); if (b) { printf ("%d\n", ret); } else { puts ("invalid!"); } return 0; }