Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Global variables are stored within the JSON file, how do I declare them as global variables when I read them out in my C++ program? #1476

Closed
XIAY0009 opened this issue Feb 11, 2019 · 2 comments
Labels
kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation

Comments

@XIAY0009
Copy link

Dear Nlohmann,

Thanks so much for the library! It is relatively user friendly :)

I am working on a project, which I keep the variables in a JSON file, and intend to read them out into my C++ program. I can do that, but the problem is that these variables are actually global variables. By reading them out in my main function, these variables are essentially local to the main function. Which is not what I require. I am not sure how could I make these variables global, your help will be much appreciated!

int main() {
std::ifstream in("/LearnJSON/test2.json");
json file = json::parse(in);

//auto size = file.size();
//file["size"] = size;
std::cout << file.at("pi") << '\n';
std::cout << std::setw(4) << file << '\n';
float pi_value = file.at("pi"); //Example I will like to make pi_value a global variable, but currently I can't
std::cout << "Value of pi is: " << pi_value << '\n';
return 0; 

}

@nickaein
Copy link
Contributor

What issue do you have? You can still define your variables as global and assign them inside the main function:

float pi_value;

int main()
{
    std::ifstream fin("settings.json");
    json j_settings = json::parse(fin);

    // assign values to global variables from JSON data
    pi_value = j_settings["pi"];
    ...
}

Does that solves your problem?

@XIAY0009
Copy link
Author

Yes, that does !! Thanks

@nlohmann nlohmann added kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation labels Feb 13, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation
Projects
None yet
Development

No branches or pull requests

3 participants