Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- struct num {
- const char s[10]; /*number string*/
- int i; /*index inside string*/
- };
- int compare_num(struct num * n, int c) {
- if (n->s[n->i]==c) {
- if (!c) { /*c will only be 0 when comparing to end of number string*/
- n->i=0;
- return 1;
- }
- n->i++;
- return compare_num(n,0); /*check if end of number string has been reached*/
- } else if (c=='i' && n->i==3 && n->s[0]=='n') {
- n->i=2; /*special fix for ninine*/
- } else if (c && n->i) {
- n->i=0;
- return compare_num(n,c); /*try to find number string again from beginning*/
- }
- return 0;
- }
- int main(int argc, char ** argv) {
- int c; /*chars fom file*/
- int first=0, last=0, sum=0; /*puzzle stuff*/
- int puzzle; /*a or b*/
- struct num num_check[9] = {
- {.s="one"}, {.s="two"}, {.s="three"}, {.s="four"}, {.s="five"},
- {.s="six"}, {.s="seven"}, {.s="eight"}, {.s="nine"},
- };
- FILE * f;
- if (argc!=3) {
- printf("%s <file.txt> a|b\n",argv[0]);
- return 1;
- }
- f=fopen(argv[1],"r");
- puzzle=argv[2][0];
- while ((c=fgetc(f))!=EOF) {
- if (c>='1' && c<='9') {
- if (!first) first=c-'0';
- last=c-'0';
- } else if (c=='\n') {
- sum+=(first*10)+last;
- first=last=0;
- for (int i=0;i<9;i++) num_check[i].i=0;
- } else if (puzzle=='b') {
- for (int i=0;i<9;i++) {
- if (compare_num(& num_check[i],c)) {
- if (!first) first=i+1;
- last=i+1;
- }
- }
- }
- }
- printf("Sum:%d\n",sum);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment