cstring - C - How to read a string line by line? -
in c program, have string want process 1 line @ time, ideally saving each line string, doing want said string, , repeating. have no idea how accomplished, though.
i thinking of using sscanf. there "read pointer" present in sscanf there if reading file? alternative doing this?
here's example of how can efficiently, if allowed write long string:
#include <stdio.h> #include <string.h> int main(int argc, char ** argv) { char longstring[] = "this long string.\nit has multiple lines of text in it.\nwe want examine each of these lines separately.\nso that."; char * curline = longstring; while(curline) { char * nextline = strchr(curline, '\n'); if (nextline) *nextline = '\0'; // temporarily terminate current line printf("curline=[%s]\n", curline); if (nextline) *nextline = '\n'; // restore newline-char, tidy curline = nextline ? (nextline+1) : null; } return 0; }
if you're not allowed write long string, you'll need make temporary string each line instead, in order have per-line string nul terminated. this:
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char ** argv) { const char longstring[] = "this long string.\nit has multiple lines of text in it.\nwe want examine each of these lines separately.\nso that."; const char * curline = longstring; while(curline) { const char * nextline = strchr(curline, '\n'); int curlinelen = nextline ? (nextline-curline) : strlen(curline); char * tempstr = (char *) malloc(curlinelen+1); if (tempstr) { memcpy(tempstr, curline, curlinelen); tempstr[curlinelen] = '\0'; // nul-terminate! printf("tempstr=[%s]\n", tempstr); free(tempstr); } else printf("malloc() failed!?\n"); curline = nextline ? (nextline+1) : null; } return 0; }
Comments
Post a Comment