OneBite.Dev - Coding blog in a bite size

Convert Variable From String To Boolean In C++

Code snippet for how to Convert Variable From String To Boolean In C++ with sample and detail explanation

In C++, you may come across situations where you need to convert a string variable to a boolean. Regardless of whether you are a beginner or an experienced programmer, understanding how to perform these conversions can be crucial. This article will guide you through both the process and the explanation of a code snippet that accomplishes this task.

Code Snippet: String to Boolean Conversion

#include <iostream>
#include <string>
#include <boost/algorithm/string.hpp>

int main(){
     std::string stringsample = "true";
     bool converted = boost::iequals(stringsample, "true");
     std::cout << std::boolalpha << converted; // outputs: true
     return 0;
}

Code Explanation: String to Boolean Conversion

Let’s break down each step of this code snippet to understand it clearly.

First, the iostream, string, and boost/algorithm/string libraries are being included. The iostream library allows for input and output in C++, while the string and boost libraries are used for string manipulations.

#include <iostream>
#include <string>
#include <boost/algorithm/string.hpp>

In the main function, a string variable stringsample is declared and assigned with the string true.

std::string stringsample = "true";

In the next line, the Boost library’s function iequals() is used to compare whether the string variable stringsample is equal to “true”. The iequals() function performs a case-insensitive comparison, which means it can deal with any case scenarios. iequals() returns a boolean result. The result is then stored in the bool variable converted.

bool converted = boost::iequals(stringsample, "true");

The std::boolalpha manipulator is used with cout to print the boolean value as true or false instead of 1 or 0. In this case, it prints true, since the string “true” was stored in stringsample.

std::cout << std::boolalpha << converted; // outputs: true

This is the simple yet practical way of converting a string to a boolean in C++. Regardless of the complexity of your project, this understanding can often come in handy.

c-plus-plus