gpt4 book ai didi

c++ - 如何避免这种嵌套的 if 语句?

转载 作者:行者123 更新时间:2023-12-04 07:47:45 25 4
gpt4 key购买 nike

我想检查是否文件存在于两个不同的路径中。如果第一个没有,请检查第二个。

filepath1 = "/path1/file.txt"
filepath2 = "/path2/file.txt"
file_descriptor = open(filepath1)

if ( !file_descriptor.open() )
{
print("file 1 did not work");

//try file 2
file_descriptor = open(filepath2);
if( !file_descriptor.open() )
{
print("could not open file 2. exiting.");
return false;
}
}

//we get here and file_descriptor should point to a valid file
read_file(file_descriptor);
return true;
如何避免嵌套 if陈述?最好,我不想嵌套 if可读性声明。
这里的问题是,如果第一个有效,我不希望它检查第二个 if陈述。
我想过使用:
  • goto (我想避免这种情况)
  • bool 值来检查一个是否有效(但现在我要引入额外的变量)
  • 最佳答案

    我想这种模式非常普遍:您可以尝试任意数量的路径:

    auto filepath1 = "/path1/file.txt";
    auto filepath2 = "/path2/file.txt";
    // We assume file_descriptor has been declared earlier

    for (const auto fpath: {filepath1, filepath2})
    {
    file_descriptor = open(fpath)
    if (file_descriptor.open())
    break;
    else
    printf("file %s did not work\n", fpath);
    }
    if (!file_descriptor.open()) return false; // or throw

    read_file(file_descriptor);
    return true;

    关于c++ - 如何避免这种嵌套的 if 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67141800/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com