C++数据存在或不存在处理方法

此文来源于👉 【76】【Cherno C++】【中字】如何处理OPTIONAL数据_哔哩哔哩_bilibili

有一个返回的函数, 比如正在读取一个文件,但是如果这个文件不能被读取,会发生什么,虽然读取失败,但我们仍然需要从函数中返回一些东西,返回一个空字符串没有意义。

如果文件是空的,应有办法看到数据存在或不存在,而std::optional可以给我们一些帮助,此特性在C++17加入。

std::optional版本

例子:

#incldue <iostream>
#include <fstream>

std::string ReadStringFromFile(const std::&string filepath, bool& outSuccess) {
    std::ifstream stream(filepath);
    if (stream) {
        std::string result;
        // read file
        stream.close();
        outSuccess = true;
        return result;
    }
    outSuccess = false;
    return {};
}

int main(void) {
    bool fileOpenedSuccessfully;
    std::string data = ReadStringFromFile("data.txt", fileOpenedSuccessfully);
    if (fileOpenedSuccessfully) {
        //...
    } else {
        //...
    }
    
    return 0;
}

std::optional版本

#include <iostream>
#include <fstream>
#include <optional>

std::optional<std::string> ReadStringFromFile(const std::string& filepath) {
    std::ifstream stream(filepath);
    if (stream) {
        std::string result;
        // read file
        stream.close();
        return result;
    }
    return {};
}

int main(void) {
    std::optional<std::string> data = ReadStringFromFile("data.txt");
    
    std::string value = data.value_or("Not present");// 如果数据确实存在std::optional中,它将返回给我们那个字符串。如果不存在,它将返回我们传入的任何值,比如" Not present "
    std::cout << value << '\n';
    
    if (data.has_value()) {
        std::cout << "File read successfully!\n"; 
    } else {
        std::cout << "File could not be opend!\n"; 
    }
    
    std::cin.get();
    return 0;
}
Licensed under CC BY-NC-SA 4.0