首页 > 解决方案 > 从 JSON 字符串 C++ 读取时出现字符串下标超出范围错误

问题描述

我正在尝试创建一个返回 JSON 属性元素的函数。

string Json_obj::get_attribute(const string& attribute) {
    size_t found = body_.find(attribute);
    char eos = ',';
    string element;
    if (found == string::npos) {
        cerr << "Not found attribute" << endl;
    }
    else { //if attribute exists
    
        size_t found_trim = found + attribute.length() + 3; //start after first quote ' mark
        size_t c = found_trim;

        while (body_[c] != eos) {
            
            element = element + body_[c];
            c++;
        }
    }
    return element;
}

例如在正文中:"mrkl_root":"1234567890","time":123,"bits":456,

get_attribute("mrkl_root")应该返回:1234567890

相反,我得到一个字符串下标超出范围错误。

提前致谢。

标签: c++jsonstringsubscript

解决方案


推荐阅读