15.5. Parsing quoted recordsΒΆ
Parsing interprets characters according to a format. Our format is two
quoted, nonempty city names followed by a nonnegative integer distance.
Reading each record with getline lets us report malformed records one
line at a time.
std::istringstream from <sstream> reads from a string using the same
extraction interface as a file stream. std::quoted from <iomanip>
handles quoted names, including escaped quotes. Check the opening quote
explicitly when the file format requires it: std::quoted also accepts an
unquoted word if there is no opening quote.
1#include <iomanip>
2#include <iostream>
3#include <sstream>
4#include <string>
5
6struct route_record {
7 std::string origin;
8 std::string destination;
9 int distance = 0;
10};
11
12bool parse_record(const std::string& line, route_record& record) {
13 std::istringstream input(line);
14 route_record parsed;
15 input >> std::ws;
16 if (input.peek() != '"' || !(input >> std::quoted(parsed.origin))) {
17 return false;
18 }
19 input >> std::ws;
20 if (input.peek() != '"' || !(input >> std::quoted(parsed.destination))) {
21 return false;
22 }
23 if (!(input >> parsed.distance) || parsed.distance < 0 ||
24 parsed.origin.empty() || parsed.destination.empty()) {
25 return false;
26 }
27 input >> std::ws;
28 if (!input.eof()) {
29 return false;
30 }
31 record = parsed;
32 return true;
33}
34
35int main() {
36 route_record record;
37 if (parse_record(R"("San Diego" "Los Angeles" 120)", record)) {
38 std::cout << record.origin << " -> " << record.destination
39 << ": " << record.distance << '\n';
40 }
41}
A temporary parsed record prevents partially updating the caller's record
on failure. The final whitespace check rejects trailing junk such as 120km.
The raw string literal in main lets the example contain double quotes
without backslash escapes. An ordinary string literal with \" escapes
would work too.
This format deliberately uses plain digits for distances. The next section shows how to handle a separate format that permits commas.
What does parsing mean in the programming sense?
The character used to escape a quote in an ordinary string literal is a .
std::string::substr takes a starting and an optional .