Friday, 15 March 2013

ifstream - Count End of Line in C++ whilst reading the 'words' -



ifstream - Count End of Line in C++ whilst reading the 'words' -

i'm writing programme first step reads ~30mb text files. these files series of numbers between 0 , 255, occasional line breaks (imagej text images, via rgb stacks). can read info vector<int> without problems, , form vector<vector<int> > rgb part also. however, i'd know height , width of images.

the total available via myvector[0,1,2].size(), unless know aspect ratio can't height/width this.

if utilize file.get(nextchar); if (nextchar == '\n'){...} code go on read across, afaik.

i tried reading characters on line separately reading in files, in add-on increased runtime (which isn't such big deal), have more serious problem in files contain tab spaces, not real spaces, whilst thought each number 4 characters, eg 123(space) or 12(space)(space) etc, turns out they'd 123(tab) , 12(tab), have different character counts.

how can count words per line? illustration code below:

void imagestack::readfile(const char *file, std::vector<int> &values) { std::ifstream filestream; filestream.open(file); if (!filestream.fail()) { std::cout<< "file opened successfully: " << file << std::endl; int countw=0; char next; while (!filestream.eof()) { int currentvalue; filestream >> currentvalue; values.push_back(currentvalue); countw++; if (filestream.get(next)=='\n') // doesn't work, think if used filestream.get(next); // if (next == '\n') check correctly, // move file marker { std::cout<< "countw = " << countw << std::endl; } } filestream.close(); values.pop_back(); } else { std::cout << "file did not open! filename " << file << std::endl; } }

code below doesn't count accurately:

std::vector<int> imagestack::getdimensions(const std::string filename) { std::vector<int> dim(2); std::stringstream rfn; rfn << filename << "r"; std::string rfilename = rfn.str(); const char *file_ptr; file_ptr = rfilename.c_str(); std::ifstream file; file.open(file_ptr); int widthcount=-1, heightcount=-1; if (!file.fail()) { char next; int counterw = 0; int counterh = 0; while(file.get(next)) { counterw++; if (next == '\n') { counterh++; if (widthcount == -1) { std::cout << "the first line has " << counterw << " characters." << std::endl; } if (widthcount != -1 && widthcount != counterw) { //~ std::cout<< "the width counter didn't same number every time!" << std::endl; //~ std::cout<< "widthcount = " << widthcount << std::endl; //~ std::cout<< "counterw = " << counterw << std::endl; } widthcount = counterw; counterw = 0; } heightcount = counterh; } file.close(); } //~ std::cout << "values found width , height " //~ << widthcount << ", " << heightcount << std::endl; dim[0] = ((widthcount-1)/4); dim[1] = heightcount; homecoming dim; }

c++ ifstream word-count line-count

No comments:

Post a Comment