Search code examples
c++booleanprogram-entry-point

Convert char to bool (passing bool to main)


Is there a recommended/correct/safer way to pass a bool argument to your main function?

Are this

$ ./my_software true

with this as my_software:

int main(argc, argv* []){

    bool my_bool = argv[1];

    return 0;
}

and this

$ ./my_software 1

with this as my_software:

int main(argc, argv* []){

    bool my_bool = atoi(argv[1]);

    return 0;
}

equivalent? Am I missing a conversion in the first one?


Solution

  • C++ streams can handle this. Don't forget to check that argv[1] actually exists !

    #include <sstream>
    //...
    std::stringstream ss(argv[1]);
    bool b;
    
    if(!(ss >> std::boolalpha >> b)) {
        // Parsing error.
    }
    
    // b has the correct value.
    

    Live on Coliru

    Putting in the std::boolalpha stream manipulator enables parsing "true" and "false", leaving it out will let it parse "0" and "1".