在 c++ 中将 json 值转换为 int

Convert json value to int in c++

本文关键字:转换 int json c++ 中将      更新时间:2023-10-16

我正在使用 c++ 读取 json 值

Json::Reader reader

并且该值存储在Json::Value root

这个根包含"age"和"id",我想将root["age"]转换为int。

我尝试使用 .str() 将其转换为字符串,但无法获取。

有什么建议吗?

jsoncpp中,它们在Json::Value对象上提供了帮助程序方法。 只需对值调用 asInt() 方法即可对其进行转换。

int ageAsInt = root["age"].asInt()

你应该能够使用

std::stoi( string )

取自 http://en.cppreference.com/w/cpp/string/basic_string/stol 的例子

#include <iostream>
#include <string>
int main()
{
    std::string test = "45";
    int myint = std::stoi(test);
    std::cout << myint << 'n';
}

如果不能直接转换为 int,请先转换为字符串,然后再转换为 int

                    string age = root["age"].asString();
                    int age2 = std::stoi(age);