-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoptional_type.cpp
More file actions
32 lines (27 loc) · 842 Bytes
/
Copy pathoptional_type.cpp
File metadata and controls
32 lines (27 loc) · 842 Bytes
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
#include<iostream>
#include<optional>
#include<fstream>
#include<string>
std::optional<std::string> ReadFileAsString(const std::string& filePath) {
std::ifstream stream(filePath);
if (stream) {
std::string result;
// read file
stream.close();
return result;
}
return {};
}
int main() {
auto data = ReadFileAsString("data.txt");
// if data is present then it will have the file content, else it will have the default value
std::string value = data.value_or("This is the default value");
// you can also do if(data)
if(data.has_value()) {
std::cout << "File read successfully" << std::endl;
std::cout << value << std::endl;
} else {
std::cout << value << std::endl;
std::cout << "Not able to read the file" << std::endl;
}
}