scanf.c 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. #include <stdarg.h>
  2. #include <stdio.h>
  3. struct params {
  4. short sa;
  5. int ia;
  6. int ib;
  7. int ic;
  8. float fa;
  9. double da;
  10. int *ptr;
  11. char c;
  12. char string[20];
  13. };
  14. void test(char* fmt_in, char* input, struct params *p, ...) {
  15. va_list args;
  16. va_start(args, p);
  17. int ret = vsscanf(input, fmt_in, args);
  18. va_end(args);
  19. printf(
  20. "%d, { sa: %hhd, ia: %d, ib: %d, ic: %d, fa: %f, da: %lf, ptr: %p, char: %c, string: %s }\n",
  21. ret, p->sa, p->ia, p->ib, p->ic, p->fa, p->da, p->ptr, p->c, p->string
  22. );
  23. }
  24. int main(int argc, char ** argv) {
  25. struct params p = { .c = 'a' };
  26. test("%hhd %d", "12 345", &p, &p.sa, &p.ia);
  27. test("%x %i %i", "12 0x345 010", &p, &p.ia, &p.ib, &p.ic);
  28. test("%f.%lf", "0.1.0.2", &p, &p.fa, &p.da);
  29. test("%p", "0xABCDEF", &p, &p.ptr);
  30. test("%s", "Hello World", &p, &p.string);
  31. test("%3i", "0xFF", &p, &p.ia);
  32. test("%c%3c", "hello", &p, &p.c, &p.string);
  33. test("test: %2i%n", "test: 0xFF", &p, &p.ia, &p.ib);
  34. test("hello world%%", "hello world%", &p);
  35. }