fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. enum { NLOTTERY = 6 }; // number of lottery numbers
  6.  
  7. // read line from `stream`
  8. // fail if input line is too long (larger than maxsize)
  9. // return < 0 on error
  10. // return 0 on success
  11. static int readline(FILE* stream, char *line, size_t maxsize) {
  12. char *s = NULL;
  13. if ((s = fgets(line, maxsize, stream)) == NULL || strlen(s) == (maxsize-1))
  14. // can't read from stream or line is too long
  15. return -1;
  16. return 0;
  17. }
  18.  
  19. int main() {
  20. FILE* fp = stdin; // read from stdin
  21.  
  22. // read number of records
  23. char line[BUFSIZ];
  24. if (readline(fp, line, sizeof(line)) < 0) {
  25. perror("readline: n");
  26. exit(EXIT_FAILURE);
  27. }
  28. int n = -1;
  29. n = atoi(line); //note: ignore errors
  30.  
  31. // process records
  32. int i = 0;
  33. for ( ; i < n; ++i) {
  34. // read first, last name
  35. if (readline(fp, line, sizeof(line)) < 0) {
  36. perror("readline: first, last name");
  37. exit(EXIT_FAILURE);
  38. }
  39. char firstname[sizeof(line)], lastname[sizeof(line)];
  40. if (sscanf(line, "%s %s", firstname, lastname) != 2) {
  41. // there must be exactly two words in the line
  42. perror("sscanf: firstname, lastname");
  43. exit(EXIT_FAILURE);
  44. }
  45.  
  46. // lottery numbers
  47. if (readline(fp, line, sizeof(line)) < 0) {
  48. perror("readline: lottery numbers");
  49. exit(EXIT_FAILURE);
  50. }
  51. char* token = NULL, *saveptr = NULL;
  52. char* str = line;
  53. int numbers[NLOTTERY];
  54. size_t j = 0;
  55. for ( ; j < sizeof(numbers)/sizeof(*numbers); ++j, str=NULL) {
  56. if ((token = strtok_r(str, " ", &saveptr)) == NULL)
  57. break;
  58. numbers[j] = atoi(token); //NOTE: ignore errors, else use strtol()
  59. if (numbers[j] < 0 || numbers[j] > 53) {
  60. fprintf(stderr, "error: number is not in range %d\n", numbers[j]);
  61. exit(EXIT_FAILURE);
  62. }
  63. }
  64. if (j != sizeof(numbers)/sizeof(*numbers)) {
  65. // there must be exactly NLOTTERY numbers in the line
  66. fprintf(stderr, "error: %s\n", "strtok_r");
  67. exit(EXIT_FAILURE);
  68. }
  69.  
  70. //
  71. printf("first name: %s\tlast name: %s\t numbers: ", firstname, lastname);
  72. for (j = 0; j < sizeof(numbers)/sizeof(*numbers); ++j)
  73. printf("%d ", numbers[j]);
  74. puts("");
  75. }
  76. exit(EXIT_SUCCESS);
  77. }
  78.  
Success #stdin #stdout 0.02s 1724KB
stdin
2
Joe Flacco
1 3 5 6 7 8
Tom Brady
7 9 10 15 52 53
stdout
first name: Joe	last name: Flacco	 numbers: 1 3 5 6 7 8 
first name: Tom	last name: Brady	 numbers: 7 9 10 15 52 53