2.4.3 Processing a File

As you saw in the previous example, you can read in a file line by line in a while loop.

string line;
while (true) {
    getline(in, line);  
    if (in.fail()) break;

    // process line
}

Each time through the loop, the line variable gets updated with the next line. Once you loop again, the previous line is lost, so you need to process that line in the loop.

Basic Line Processing

The simplest way to deal with the line in the loop is to add it to a string vector. By creating the vector before the loop and adding the line to the vector, you will end up with a vector with all the lines after the loop.

string line;
vector<string> input;
while (true) {
    getline(in, line);  
    if (in.fail()) break;

    input.push_back(line);
}

This method can be considered a basic line process since you will most likely need to do something with each line after your input loop.

Detailed Line Processing

Since you are already looping through all the lines, it may be more convenient to break down a line further as you are looping.

In this example, you will see how this can be processed and printed as you read in the data.

Last updated