c++ - Segmentation Fault searching for End of Line -
i'm writing code counts amount of lines , characters of file.
#include <fstream> #include <iostream> #include <stdlib.h> using namespace std; int main(int argc, char* argv[]) { ifstream read(argv[1]); char line[256]; int nlines=0, nchars=0, ntotalchars=0; read.getline(line, 256); while(read.good()) / { nchars=0; int i=0; while(line[i]!='\n') { if ((int)line[i]>32) {nchars++;} i++; } nlines++; ntotalchars= ntotalchars + nchars; read.getline(line, 256); } cout << "the number of lines "<< nlines << endl; cout << "the number of characters "<< ntotalchars << endl; } the line while(line[i]!='\n') seems cause of following error
segmentation fault (core dumped)
i can't figure out what's wrong. internet tells me i'm checking end of line correctly far can tell.
your code not find '\n' because discarded input sequence. documentation of getline:
the delimiting character newline character [...]: when found in input sequence, extracted input sequence, discarded , not written s.
you should searching '\0':
while(line[i]) { if ((int)line[i]>32) {nchars++;} i++; }
Comments
Post a Comment