I am trying to count the number new lines, '\n', in an input file that i am reading using getline(). I think that when you use getline(), the newline character gets overwritten by a NULL character ( '\0'). So how would you count the number of newlines
1 2 3 4 5 6 7 8
while (!read.eof())
{
read.getline(str,100,'\n');
out<<str<<endl; //print the lines to the output file as i get them
}
getline doesn't do anything to the '\n' character - it just skips over it. You could count how often you can call getline before hitting eof, or you could open your file in binary mode and just directly search for '\n' characters. (note that actually, '\n' isn't always written to the file if you have that in a string - for example, on windows ostreams will convert '\n' s to '\r' '\l' (carriage return + line feed) because that's the line terminator on windows).
I personally would have just gone with the "count the possible getlines" variant (especially if you need the lines anyways). As I said, now you have to search for line terminators - which are platform specific.
Ok, do i need to open in binary mode so i can count the
no. of getlines? if so HOW do you count the no. Of getlines or no.
of terminating characters '\0'
you should have a: read.open("somefile.txt"); or similar, if I am correct.
if you look up the fstream::open() in the reference section, you would learn that Open can take a second parameter usually std::ios::binary or others. Which are listed there. http://www.cplusplus.com/reference/iostream/fstream/open/
and I wouldn't need any thing like that, with the getline(std::fstream, std::string) this would get most of the data to the "\n" for me, and I would do a simple increment on a while. This function is on of the global functions out there. It isn't tied to a class.