fork download
  1. #include <stdio.h>
  2. #include <assert.h>
  3. #include <stdlib.h>
  4. #include <errno.h>
  5.  
  6. struct Foo
  7. {
  8. int a;
  9. int b;
  10. int c;
  11.  
  12. int state;
  13. };
  14.  
  15. void on_number(void *opaque, long value)
  16. {
  17. assert(opaque);
  18. struct Foo* ctx = (struct Foo*)(opaque);
  19. if (ctx->state == 0)
  20. ctx->a = value;
  21. if (ctx->state == 1)
  22. ctx->b = value;
  23. if (ctx->state == 2)
  24. ctx->c = value;
  25. ctx->state++;
  26. }
  27.  
  28. void extract_numbers(const char *str, int base, void *opaque, void (*on_number_cb)(void*,long))
  29. {
  30. while (*str)
  31. {
  32. char *enptr = NULL;
  33. long value = strtol(str, &enptr, base);
  34. if (str == enptr)
  35. {
  36. str++;
  37. continue;
  38. }
  39. else
  40. {
  41. str = enptr;
  42. }
  43.  
  44. if (on_number_cb)
  45. on_number_cb(opaque, value);
  46. }
  47. }
  48.  
  49. int main(void)
  50. {
  51. const char* str = "5 used hard 4 label 10";
  52. struct Foo ctx = {0};
  53.  
  54. extract_numbers(str, 10, &ctx, on_number);
  55.  
  56. printf("ctx.a = %d, ctx.b = %d, ctx.c = %d\n", ctx.a, ctx.b, ctx.c);
  57.  
  58. return 0;
  59. }
  60.  
Success #stdin #stdout 0s 2156KB
stdin
Standard input is empty
stdout
ctx.a = 5, ctx.b = 4, ctx.c = 10