Guest User

Untitled

a guest
Dec 12th, 2023
479
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.41 KB | Source Code | 0 0
  1. #include <stdio.h>
  2.  
  3. struct num {
  4.     const char s[10]; /*number string*/
  5.     int i; /*index inside string*/
  6. };
  7.  
  8. int compare_num(struct num * n, int c) {
  9.     if (n->s[n->i]==c) {
  10.         if (!c) { /*c will only be 0 when comparing to end of number string*/
  11.             n->i=0;
  12.             return 1;
  13.         }
  14.         n->i++;
  15.         return compare_num(n,0); /*check if end of number string has been reached*/
  16.     } else if (c=='i' && n->i==3 && n->s[0]=='n') {
  17.         n->i=2; /*special fix for ninine*/
  18.     } else if (c && n->i) {
  19.         n->i=0;
  20.         return compare_num(n,c); /*try to find number string again from beginning*/
  21.     }
  22.     return 0;
  23. }
  24.  
  25. int main(int argc, char ** argv) {
  26.     int c; /*chars fom file*/
  27.     int first=0, last=0, sum=0; /*puzzle stuff*/
  28.     int puzzle; /*a or b*/
  29.     struct num num_check[9] = {
  30.         {.s="one"}, {.s="two"}, {.s="three"}, {.s="four"}, {.s="five"},
  31.         {.s="six"}, {.s="seven"}, {.s="eight"}, {.s="nine"},
  32.     };
  33.     FILE * f;
  34.  
  35.     if (argc!=3) {
  36.         printf("%s <file.txt> a|b\n",argv[0]);
  37.         return 1;
  38.     }
  39.     f=fopen(argv[1],"r");
  40.     puzzle=argv[2][0];
  41.     while ((c=fgetc(f))!=EOF) {
  42.         if (c>='1' && c<='9') {
  43.             if (!first) first=c-'0';
  44.             last=c-'0';
  45.         } else if (c=='\n') {
  46.             sum+=(first*10)+last;
  47.             first=last=0;
  48.             for (int i=0;i<9;i++) num_check[i].i=0;
  49.         } else if (puzzle=='b') {
  50.             for (int i=0;i<9;i++) {
  51.                 if (compare_num(& num_check[i],c)) {
  52.                     if (!first) first=i+1;
  53.                     last=i+1;
  54.                 }
  55.             }
  56.         }
  57.     }
  58.     printf("Sum:%d\n",sum);
  59.     return 0;
  60. }
  61.  
Advertisement
Add Comment
Please, Sign In to add comment