#include <iostream>
#include <fstream>
#include <string>
#include <optional>//c++17
// how to deal with data that may or may not be there.
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 {};//return the optional.
}
int main(void)
{
std::optional<std::string> data = ReadFileAsString("test/optionalTest.txt");
// value_or():if the data from the optional is present will return to us that string,
// if not it will return "Not present" in this case.
std::string value = data.value_or("Not present");
std::cout << value << std::endl;
if (data.has_value())//or if(data)
{
std::cout << "File read successfully!\n";
}
else
{
std::cout << "File could not be opened!\n";
}
std::cin.get();
}
【Cherno的C++视频】How to deal with optional data in C++
最新推荐文章于 2024-09-16 16:07:55 发布