fork download
  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. int main(void) {
  5. char format[20] = {0};
  6. char buf[50] = {0};
  7. char str[] = "Hello World! How are you?";
  8. size_t howMuchToRead = 8;
  9.  
  10. /* Using sscanf - till whitespace or size specified */
  11. snprintf(format, sizeof format, "%%%zus", howMuchToRead);
  12. sscanf(str, format, buf);
  13. printf("Using sscanf with %%8s format :%s\n", buf);
  14.  
  15. /* Using sscanf - read everything upto newline */
  16. snprintf(format, sizeof format, "%%%zu[^\n]", howMuchToRead);
  17. sscanf(str, format, buf);
  18. printf("Using sscanf with %%8[^\\n] format :%s\n", buf);
  19.  
  20. /* Using precision specifier */
  21. snprintf(format, sizeof format, "%%.%zus", howMuchToRead);
  22. snprintf(buf, sizeof buf, format, str);
  23. printf("Using precision specifier :%s\n", buf);
  24. return 0;
  25. }
Success #stdin #stdout 0.02s 1720KB
stdin
Standard input is empty
stdout
Using sscanf with %8s format :Hello
Using sscanf with %8[^\n] format :Hello Wo
Using precision specifier :Hello Wo