Invalid overload of 'islower'
I am trying to develop a BattleShip game in C ++ and I am almost ready. For this I need my function gameOver
. My game is over when all the ships are sunk. So I am trying to count how many lowercase characters I have in the string status (from the ship). When half of the characters are in lowercase, the "ship" is destroyed and I'm ready to use the function gameOver
.
But somehow mine count_if
doesn't work and I don't know why.
Here you go:
#include <algorithm>
bool Ship::isDestroyed() const{
//This counts those chars that satisfy islower:
int lowercase = count_if (status.begin(), status.end(), islower);
return ( lowercase <= (status.length/2) ) ? true : false;
}
bool Board::gameOver() {
bool is_the_game_over = true;
for(int i = 0 ; i < ships.size() ; i++){
if( ships[i].isDestroyed() == false ) {
//There is at least one ship that is not destroyed.
is_the_game_over = false ;
break;
}
}
return is_the_game_over;
}
What am I doing wrong?
source to share
Try to change the algorithm as follows
int lowercase = count_if (status.begin(), status.end(), ::islower);
^^^
Compilers are allowed to place standard C functions in the global namespace.
Otherwise use a lambda expression like
int lowercase = count_if (status.begin(), status.end(),
[]( char c ) return islower( c ); } );
source to share
Unfortunately, the standard library has more than one overload islower
(a function from the C library and a function template from the localization library), so you can't just name the function if you don't call it.
You can convert it to the function type you want:
static_cast<int (*)(int)>(islower)
or hopefully your implementation will remove the C library into the global namespace as well std
:
::islower // not guaranteed to work
or wrap it in a lambda
[](int c){return islower(c);}
source to share