fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <errno.h>
  4.  
  5. int main() {
  6. const char *inputs[] = {
  7. "12345678901234567890", // base 10
  8. "0xFFEE", // base 16
  9. "0755", // base 8 (if base = 0)
  10. "101010", // base 2
  11. "invalid123", // invalid input
  12. };
  13.  
  14. int bases[] = {10, 0, 0, 2, 10}; // base 0 lets strtoull auto-detect
  15.  
  16. for (int i = 0; i < 5; ++i) {
  17. const char *str = inputs[i];
  18. int base = bases[i];
  19. char *endptr;
  20. errno = 0;
  21.  
  22. unsigned long long result = strtoull(str, &endptr, base);
  23.  
  24. printf("Input: \"%s\" | Base: %d\n", str, base);
  25. if (errno == ERANGE) {
  26. printf(" ➤ Overflow occurred!\n");
  27. } else if (endptr == str) {
  28. printf(" ➤ No digits were found.\n");
  29. } else {
  30. printf(" ➤ Converted value: %llu\n", result);
  31. if (*endptr != '\0') {
  32. printf(" ➤ Remaining string: \"%s\"\n", endptr);
  33. }
  34. }
  35. printf("\n");
  36. }
  37.  
  38. return 0;
  39. }
  40.  
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
Input: "12345678901234567890" | Base: 10
  ➤ Converted value: 12345678901234567890

Input: "0xFFEE" | Base: 0
  ➤ Converted value: 65518

Input: "0755" | Base: 0
  ➤ Converted value: 493

Input: "101010" | Base: 2
  ➤ Converted value: 42

Input: "invalid123" | Base: 10
  ➤ No digits were found.