string - Read Line By Line Until Integer is Found C -
trying create program takes in text file , reads line line. finds 2 integers on each line , adds them together. outputs new line original string , total new text file. need adding 2 integers, getting them each line, , putting new line text file.
input text file
good morning hello 34 127 ann 20 45 10 11 fun program , find same 90 120 news paper said 56 11 how 20 5 line number 90 34
outputs first like: , continue on
good morning hello 161
code:
int processtextfile(char * inputfilename, char * outputfilename) { file *fp = fopen(inputfilename, "r");//open file to read char buff[1024]; char *p, *p1; int num; while (fgets(buff, 1024, fp)!=null) { printf("%s\n", buff); while(scanf(buff, "%*[^0-9]%d", &num)== 1) printf("%d\n", num); //fscanf(fp, "%s", buff); } return 0; }
edit!!!!::
so i've been able accomplish this. how sort number produced? example:
time money 52 here 3 21
would output new text file in order like
here 3 21 time money 52
my version using strcspn()
supposed work stdin input , stdout output. (so can executable <textfile >newtextfile
)
#include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { char line[1000]; while (fgets(line, sizeof line, stdin)) { char *ptr; size_t x = strcspn(line, "0123456789"); if (line[x]) { errno = 0; int n1 = strtol(line + x, &ptr, 10); if (*ptr && !errno) { errno = 0; int n2 = strtol(ptr, &ptr, 10); if (*ptr && !errno) { int n3 = n1 + n2; printf("%.*s%d\n", (int)x, line, n3); } else { printf("%s", line); // line includes enter } } else { printf("%s", line); // line includes enter } } else { printf("%s", line); // line includes enter } } return 0; }
the same version without error checking
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { char line[1000]; while (fgets(line, sizeof line, stdin)) { char *ptr; size_t x = strcspn(line, "0123456789"); int n1 = strtol(line + x, &ptr, 10); int n2 = strtol(ptr, &ptr, 10); int n3 = n1 + n2; printf("%.*s%d\n", (int)x, line, n3); } return 0; }
Comments
Post a Comment