Skip to content

Reading Formatted Input Data

Directions

With a partner, answer as many of the following questions as you can. Start with the level of difficulty you feel most comfortable with! See the code and input file below.

Questions

Easier

  1. What happens if the input file does not exist?

  2. Will it correctly process the following line of text in the input file:
    " name : Brian Fraser "

  3. What happens if the file contains the following lines:

    • a) an empty line: ""
    • b) "oops!"
    • c) "doh: something unknown"
  4. Why does it convert the age to an int instead of leaving it a string?

  5. What happens if there is no info.txt file in the current folder?

  6. What will the line "height: 2.0" print, and what about "height: 2.01"?

  7. What does {:.2f} do in processKeyValue() when processing the height?

    • What gets printed for height: 1.4441?
  8. In main()'s while loop, what does the continue do?

  9. What does this print out?
    println(">{}<", trim("\n HI \n "));

Medium

  1. What is wrong with this code which calls trim()?

    CPP
    string a = " HELLO ";
    trim(a);
    if (a == "HELLO") {
        println("Hello to you too!");
    }
    
  2. What happens with the line "Name: Bob"?

    • Why, and how could you change the code so it accepts any capitalisation?
  3. For the line "time: 10:30", what are key and value?

    • Why isn't it split at the second colon?
  4. What happens with "age: twenty"? What about "age: 20 years"? Explain the difference.

  5. What does the line "name: " print? How could you detect and report an empty value?

Hard

  1. Explain what the variable colonIdx holds.

    • a) What is its actual type?
    • b) What value is string::npos?
    • c) Explain how the code uses colonIdx, including the calls to string.substr().
  2. Suppose you delete the if block starting with if (colonIdx == string::npos).

    • What happens with the line "oops!"? Does it crash?
    • Can you explain? Hint: npos = the maximum value that can be stored in its integer data type (64 bits on my machine).
  3. If info.txt was saved on Windows, every line ends in \r. If you print each line with println("Read '{}'", line);, why does it look garbled?

    • If you print out the full line read from the file, why will it look garbled in the terminal?

Source Code readFormatted.cpp

Code also available here.

CPP
// Read a file of key:value pairs, one per line, like:
//   name: Dr. Evil
//   age: 20
//   height: 1.4441

#include <print>
#include <fstream>
using namespace std;

string trim(const string &str)
{
    string copy = str;
    while (!copy.empty() && isspace(copy.front())) {
        // Removes characters from the string starting at index of 
        // 1st arg, removing number of characters in 2nd arg.
        copy.erase(0, 1);
    }
    while (!copy.empty() && isspace(copy.back())) {
        copy.pop_back();
    }
    return copy;
}

void processKeyValue(const string &key, const string &value) 
{
    if (key == "name") {
        println("Welcome {}!", value);
    } else if (key == "height") {
        double height = stod(value);
        if (height > 2.0) {
            println("You are tall at {:.2f}m.", height);
        } else {
            println("Height is {:.2f}m", height);
        }
    } else if (key == "age") {
        int age = stoi(value);
        println("In 10 years you'll be {}!", age + 10);
    } else {
        println("WARNING: Unknown key in file: '{}'.", key);
    }
}

int main()
{
    // Open data file
    ifstream inFile("info.txt");
    if (!inFile.is_open()) {
        println("ERROR: Unable to open file.");
        exit(EXIT_FAILURE);
    }

    // Process each "key: value" line in the file
    string line;
    while (getline(inFile, line)) {

        // Check contents of the line:
        auto colonIdx = line.find(':');
        if (colonIdx == string::npos) {
            println("Skipping this line; no colon.");
            continue;
        }

        // Process the line
        string key = trim(line.substr(0, colonIdx));
        string value = trim(line.substr(colonIdx + 1));
        processKeyValue(key, value);
    }
}

Input file info.txt

Put the following in a file name info.txt in the same folder as your code.

TXT
name:Dr. Evil
age:100

---- Line skipped ----
height:1.1