1

I am trying to do something like this:

BOOST_FOREACH (const std::string& line, allLinesOf(someFileLoadedIntoString))
{
   ...
}

I wonder how to implement the allLinesOf function? Thanks!

UPDATE: Thanks for the answers. Sorry but I forgot to mention one important detail: in my case the newlines are \r\n.

Alex Jenter
  • 4,324
  • 4
  • 36
  • 61
  • Duplicate of [Is there a C++ iterator that can iterate over a file line by line?](http://stackoverflow.com/questions/2291802/is-there-a-c-iterator-that-can-iterate-over-a-file-line-by-line) (though, Jerry's answer to [How do I iterate over `cin` line by line in C++?](http://stackoverflow.com/questions/1567082/how-do-i-iterate-over-cin-line-by-line-in-c) is better than that exact duplicate). – James McNellis Nov 21 '10 at 17:16

3 Answers3

5

You can use std::getline.

std::string line;
while(std::getline(file, line)) {
    // Ohai!
}
craymichael
  • 4,578
  • 1
  • 15
  • 24
Puppy
  • 144,682
  • 38
  • 256
  • 465
  • Will it work with "\r\n" newlines? The string is loaded from a text file on Windows. – Alex Jenter Nov 21 '10 at 18:28
  • @Alex: You can specify a separator, from memory, and in addition, I believe that the MSVC STL automatically converts "\r\n" to "\n" when loading in text mode. – Puppy Nov 21 '10 at 18:31
  • 2
    The I/O Streams library performs newline translation, so when you open a file stream in text mode, it will automatically translate the platform line ending (which may be `\r\n` or something else) into the C++ line ending (`\n`). – James McNellis Nov 22 '10 at 03:25
2

Um, you can write a custom iterator for std::string that would iterate over string segments separated by newlines and pass a std::pair of such iterators to BOOST_FOREACH

1

You can use boost::tokenizer with \n token to iterate over lines.

Kirill V. Lyadvinsky
  • 97,037
  • 24
  • 136
  • 212