You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++读取Toml文件:在for循环中检查元素是否存在于字符串数组

修复你的Toml读取与权限检查代码

代码中的核心问题

  1. main函数定义错误:int main{ 缺少括号,正确写法为 int main()。
  2. 字符串集合定义错误:你试图用单个std::string对象存储多个字符串,这完全不符合语法。需改用std::vector<std::string>或字符串数组来存储允许的键列表。
  3. 变量名冲突:循环内的[k, v]中的v覆盖了外部定义的字符串集合变量v,导致后续查找逻辑指向Toml值而非你定义的允许键列表,这是功能失效的关键原因。
  4. std::find使用不规范:未包含<algorithm>头文件,且未明确指定std::命名空间,同时查找目标指向错误。
  5. 冗余的Toml查找:遍历perms.as_table()时已直接获取键值对,无需再次调用toml::find(perms, k)。

修正后的完整代码

#include <iostream>
#include <vector>
#include <algorithm>
#include <toml++/toml.h>

int main() {
    // 定义允许的键列表,用vector更灵活
    std::vector<std::string> allowed_keys = {
        "css", "css_files", "html", "html_files", "js", "js_files", 
        "php", "php_files", "all_files", "time", "user_data", 
        "edit_files", "SQL", "run_files", "download_files", 
        "requests", "WIFI", "battery"
    };

    try {
        const auto data = toml::parse("test.toml");
        const auto& perms = toml::find(data, "permissions");
        
        // 遍历permissions表中的所有键值对
        for (const auto& [key, value] : perms.as_table()) {
            // 检查当前键是否在允许列表中
            if (std::find(allowed_keys.begin(), allowed_keys.end(), key) != allowed_keys.end()) {
                std::cout << key << " is present in the allowed array\n";
            } else {
                std::cout << key << " is not present in the allowed array\n";
            }
            
            // 直接输出遍历得到的键值
            std::cout << key << ": " << value << "\n";
        }
    } catch (const toml::parse_error& e) {
        std::cerr << "Parse error: " << e.what() << "\n";
        return 1;
    } catch (const std::out_of_range& e) {
        std::cerr << "Error: " << e.what() << "\n";
        return 1;
    }

    return 0;
}

额外优化说明

  • 添加了异常捕获:处理Toml文件解析失败或找不到permissions节点的情况,提升程序健壮性。
  • 使用std::vector管理允许键:避免手动计算数组长度,同时支持动态修改。
  • 变量名语义化:将冲突的v改为allowed_keys和value,代码逻辑更清晰。

内容的提问来源于stack exchange,提问作者user20360581

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 05:40:41