how would i count the number of lines in a multiline string

how would I count the number of lines in a multiline string? example input:
4 4 4
4 4 4
4 4 4
5 5 7 ] (the ']' is the delimiter I'm using getline with a delimiter)
I've tried making a regex to find '\n' and tried tokenising the string and doing the regex there, didn't work any ideas on how I would get the number of columns?
1
2
auto num_lines = std::count( str.begin(), str.end(), '\n' ) ;
num_lines += ( !str.empty() && str.back() != '\n' ) ;
^just a note on that code, be aware it works differently than how a program like wc -l works, which will not count the last 'line' as a line if it doesn't end in a newline.
wc - l counts the number of '\n' - not the number of 'lines'! There is a subtle difference as per Borges code.

Personally I always thought this was a 'bug' in the wc -l implementation which morphed into a 'feature'!
Last edited on
POSIX defines a line in a text file as:
A sequence of zero or more non- <newline> characters plus a terminating <newline> character.


wc is correct as per POSIX:
a sequence of characters not ending in a newline character is not considered to be a 'line'.
And hence the Unix guideline: text files should end with a new line (most Unix utilities expect this to be the case).
Last edited on
Topic archived. No new replies allowed.