fork download
  1. #include <ctype.h>
  2. #include <stdio.h>
  3.  
  4. int featlinespace(FILE * stream);
  5. int fgetlineword(char * s, int n, FILE * stream);
  6.  
  7. int main(void) {
  8. int line = 1;
  9. char wordbuf[30];
  10. int count;
  11.  
  12. while (!feof(stdin)) {
  13. /* For each line, print each word */
  14. printf("Line %d:\n", line++);
  15. while ((count = fgetlineword(wordbuf, sizeof wordbuf, stdin)))
  16. printf("%d: \"%s\"\n", count, wordbuf);
  17. /* Eat newline */
  18. fgetc(stdin);
  19. }
  20. return 0;
  21. }
  22.  
  23. int featlinespace(FILE * stream) {
  24. int c;
  25. int rv = 0;
  26.  
  27. while ((c = fgetc(stream)) != EOF) {
  28. if (!isspace(c) || c == '\n') {
  29. ungetc(c, stream);
  30. break;
  31. }
  32. ++rv;
  33. continue;
  34. }
  35. return rv;
  36. }
  37.  
  38. int fgetlineword(char * s, int n, FILE * stream) {
  39. char * const end = s + n - 1;
  40. int c = 0;
  41.  
  42. featlinespace(stream);
  43. n = 0;
  44. while (s < end && (c = fgetc(stream)) != EOF) {
  45. if (isspace(c)) {
  46. ungetc(c, stream);
  47. break;
  48. }
  49. *s++ = c;
  50. ++n;
  51. continue;
  52. }
  53. *s = '\0';
  54. return n;
  55. }
  56.  
Success #stdin #stdout 0.01s 1724KB
stdin
    this is         a   
test   for  	  zikomos    
reallyreallyreallyreallyreallylongwordreally uh huh
foo bar baz
meep           meep         


2 lines above were blank
stdout
Line 1:
4: "this"
2: "is"
1: "a"
Line 2:
4: "test"
3: "for"
7: "zikomos"
Line 3:
29: "reallyreallyreallyreallyreall"
15: "ylongwordreally"
2: "uh"
3: "huh"
Line 4:
3: "foo"
3: "bar"
3: "baz"
Line 5:
4: "meep"
4: "meep"
Line 6:
Line 7:
Line 8:
1: "2"
5: "lines"
5: "above"
4: "were"
5: "blank"