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
-
What happens if the input file does not exist?
-
Will it correctly process the following line of text in the input file:
" name : Brian Fraser " -
What happens if the file contains the following lines:
- a) an empty line:
"" - b)
"oops!" - c)
"doh: something unknown"
- a) an empty line:
-
Why does it convert the age to an
intinstead of leaving it a string? -
What happens if there is no
info.txtfile in the current folder? -
What will the line
"height: 2.0"print, and what about"height: 2.01"? -
What does
{:.2f}do inprocessKeyValue()when processing the height?- What gets printed for
height: 1.4441?
- What gets printed for
-
In
main()'s while loop, what does thecontinuedo? -
What does this print out?
println(">{}<", trim("\n HI \n "));
Medium
-
What is wrong with this code which calls
trim()?CPPstring a = " HELLO "; trim(a); if (a == "HELLO") { println("Hello to you too!"); } -
What happens with the line
"Name: Bob"?- Why, and how could you change the code so it accepts any capitalisation?
-
For the line
"time: 10:30", what arekeyandvalue?- Why isn't it split at the second colon?
-
What happens with
"age: twenty"? What about"age: 20 years"? Explain the difference. -
What does the line
"name: "print? How could you detect and report an empty value?
Hard
-
Explain what the variable
colonIdxholds.- a) What is its actual type?
- b) What value is
string::npos? - c) Explain how the code uses
colonIdx, including the calls tostring.substr().
-
Suppose you delete the
ifblock starting withif (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).
- What happens with the line
-
If
info.txtwas saved on Windows, every line ends in\r. If you print each line withprintln("Read '{}'", line);, why does it look garbled?- If you print out the full
lineread from the file, why will it look garbled in the terminal?
- If you print out the full
Source Code readFormatted.cpp
Code also available here.
// 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.
name:Dr. Evil
age:100
---- Line skipped ----
height:1.1