-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathioreadwrite.cpp
More file actions
73 lines (66 loc) · 1.74 KB
/
ioreadwrite.cpp
File metadata and controls
73 lines (66 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <iostream>
#include <fstream>
#include <string>
#include <regex>
/* Created by: Lucas Saito, 12 Apr 2021
*
* This simple program uses fstream to read the textfile,
* extract the author's name using regex, and then prints
* the poem.
*
*/
class PoemReader {
public:
typedef std::ifstream input;
std::string author;
private:
std::string file_path_;
input inFile_;
input GetInput() {
input tempInput = input(file_path_);
return tempInput;
}
std::string GetAuthor() {
input tempInput = GetInput();
std::string line;
getline(tempInput, line);
tempInput.close();
// Regex to find the author's name
std::regex regexp("(?:by )(.+)");
std::smatch m;
std::regex_search(line, m, regexp);
// Case when regex finds no matches
if (m.empty() || m.size() == 1) {
return "No author found";
} else {
return m[1];
}
}
public:
PoemReader() = default;
~PoemReader() = default;
explicit PoemReader(const std::string& path)
: file_path_(path){
inFile_ = input(path.c_str());
if (inFile_.fail()) {
throw (std::runtime_error("Error opening the file, verify if the filepath is correct."));
}
inFile_.close();
author = GetAuthor();
};
void read() {
inFile_ = GetInput();
std::string line;
while (getline(inFile_, line)) {
std::cout << line << std::endl;
}
inFile_.close();
};
};
int main() {
std::string path = "../IOReadWrite/poem.txt";
PoemReader poem_reader(path);
std::cout << "A poem by: " << poem_reader.author << std::endl;
poem_reader.read();
return 0;
}