Initialize boolean array from string
Stepping over this question, I present a solution, where the boolean array
can be initialized by a string
. Thereby '0'=false
, '1'=true
and ' '=just a spacer
. This works similar to the bitset constructor.
Code
#include <iostream>
/**
* Fills boolean array based on a simple string
*
* @param[out] boolean array to be filled
* @param[in] str accepts only 0 (false), 1 (true) and space (seperator) chars in string
* @param[in] nMax maximum number of elements to write, -1 is infinite
* @returns number of writen boolen elements
*/
size_t boolArray_from_string(bool *boolArray, const std::string str, const int nMax = -1)
{
size_t size = str.size();
size_t n = 0;
int cc;
for (cc = 0; cc < size; cc++)
{
if (str.at(cc) == ' ') {continue;}
if (str.at(cc) != '0' && str.at(cc) != '1')
{
throw std::invalid_argument("str must contain only 0s, 1s and spaces.");
}
if (n == nMax)
{
throw std::invalid_argument("nMax too small for str content.");
}
if (str.at(cc) == '0')
{
boolArray[n] = false;
}
else
{
boolArray[n] = true;
}
n++;
}
return cc;
}
void print(bool *x, int nRows, int nCols)
{
for(int row=0; row<nRows; row++)
{
for(int col=0; col<nCols; col++)
{
std::cout << x[row * nCols + col] << " ";
}
std::cout << "\n";
}
std::cout << "\n\n";
};
int main()
{
bool falseArr[3][5];
boolArray_from_string(&falseArr[0][0], std::string(15, '0'), -1);
print(&falseArr[0][0], 3, 5);
bool custArr[3][5];
boolArray_from_string(&custArr[0][0], "01011 00111 11111", -1);
print(&custArr[0][0], 3, 5);
}
Output
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 1 0 1 1
0 0 1 1 1
1 1 1 1 1