fork download
  1. #include <stdio.h>
  2. #include <ctype.h>
  3.  
  4. int strToInt(const char *text)
  5. {
  6. int n = 0, sign = 1;
  7. switch (*text) {
  8. case '-': sign = -1;
  9. case '+': ++text;
  10. }
  11. for (; isdigit(*text); ++text) n *= 10, n += *text - '0';
  12. return n * sign;
  13. }
  14.  
  15. int main()
  16. {
  17. const char *samples[] = {
  18. "123", "-234", "+345", "abc", ""
  19. };
  20. enum { n = sizeof samples / sizeof *samples };
  21. for (int i = 0; i < n; ++i) {
  22. printf("strToInt(\"%s\"): %d\n", samples[i], strToInt(samples[i]));
  23. }
  24. return 0;
  25. }
Success #stdin #stdout 0s 9432KB
stdin
Standard input is empty
stdout
strToInt("123"): 123
strToInt("-234"): -234
strToInt("+345"): 345
strToInt("abc"): 0
strToInt(""): 0