Why am I getting a bad line: 1 when I run the program? The regex row expression regex row {R"(^[\w ]+( \d+)( \d+)( \d+)$)"}; appears to be correct. There is one tab to the first \d+ and two tabs to the second and third \d+. I do not know why it does not work.
// C23 Matching.cpp
#include <regex>
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
usingnamespace std;
struct bad_from_string : bad_cast {
constchar* what() const override
{
return"bad cast from string";
}
};
template<typename T> T from_string(const string& s)
{
istringstream is{ s };
T t;
if (!(is >> t)) throw bad_from_string{};
return t;
}
int main()
{
ifstream in{ "table.txt" };
if (!in) cerr << "no input file\n";
string line; // input buffer
int lineno = 0;
regex header {R"(^[\w ]+( [\w ]+)*$)"};
regex row {R"(^[\w ]+( \d+)( \d+)( \d+)$)"};
if (getline(in, line)) {
smatch matches;
if (!regex_match(line, matches, header)) {
cerr << "no header\n";
}
}
// column totals
int boys = 0;
int girls = 0;
while (getline(in, line)) {
++lineno;
smatch matches;
if (!regex_match(line, matches, row))
cerr << "bad line: " << lineno << '\n';
if (in.eof()) cout << "at eof\n";
// check row:
int curr_boy = from_string<int>(matches[1]);
int curr_girl = from_string<int>(matches[2]);
int curr_total = from_string<int>(matches[3]);
if (curr_boy + curr_girl != curr_total) cerr << "bad row sum \n";
if (matches[1] == "Alle") {
if (curr_boy != boys) cerr << "boys don't add up\n";
if (curr_girl != girls) cerr << "girls don't add up\n";
if (!(in >> ws).eof()) cerr << "characters after total line";
return 0;
}
// update totals
boys += curr_boy;
girls += curr_girl;
}
cerr << "didn't find total line";
}
Here is my table.txt file. There are tabs between words and numbers. Antal Drenge is Danish for boys, and Antal Piger is Danish for girls. Elever Ialt is the row total of boys and girls.
1. An interesting for statement. Where do you find the syntax for this type of for statement?
2. What is the purpose of line 19, d = {};? It appears that it is not needed.
Now that the program reads the rows, how do you get line 62 in my program to execute?
It clears the contents of d (sets integers to zero, strings to empty strings etc.)
Here, the empty braced-init-list{} denotes a value-initialised anonymous temporary object of type data.
> how do you get line 62 in my program to execute?
normb > You are not capturing the column KLASS so line 62 will never evaluate to true.