← Samples

Read line-by-line

1234567891011121314#include <sstream> #include <string> int main() { std::istringstream stream{"This stream\n" "contains many\n" "lines.\n"}; std::string line; while (std::getline(stream, line)) { // Process line } }

This sample is licensed under the CC0 Public Domain Dedication.


Process the contents of an input stream line-by-line.


We use a std::istringstream as an example input stream (lines 6–8) containing multiple lines (separated by \n). This stream could be replaced with std::cin or a file stream, for example. On line 9, we introduce a std::string into which we will read each line of the stream.

On lines 11–13, we use a while loop to iterate over each line of the stream. The condition of the loop is a call to std::getline, which extracts lines from stream into line. The result of this call will evaluate to false only when the extraction fails, such as when there are no lines left to extract.


  • Joseph Mansfield

Last Updated

03 April 2015


Fork this sample on GitHub