string中的所有元素都是低的
All elements in string are lower
大家晚上好!为了完成我的《战舰》游戏,我需要一个gameOver函数来发现字符串的一半字符是否较低。我的意思是,每个字符串代表一艘船:-例如,我有一艘船,用字符P表示,大小为4,他的字符串状态将是:PPPP。
每次我攻击船的位置,我击中的字符会降低。船在一半被摧毁时下沉,因为一半的碳是低的。
bool Ship::isDestroyed() const{
int tam;
tam = status.length();
cout << tam;
int i = 0;
int lowercase;
lowercase = 0;
lowercase = 0;
for (int i = 0; i < tam; i++){
if (islower(status[i])){
lowercase++;
cout << "lowercase" << lowercase << endl;
}
}
cout << "lowercase" << lowercase << endl;
if (lowercase == tam / 2){
cout << (int)tam / 2 << endl;
cout << "lowercase fail" << lowercase << endl;
return true;
}
else
return false;
}
bool Board::gameOver() {
for (int i = 0; i < ships.size() - 1; i++){
if ((ships[i].isDestroyed())){
return false;
continue;
}
}
cout << "GameOver" << endl;
return true;
}
ships.size()
- ships向量,里面有Ship对象。
我猜问题出在gameOver上,但我真的可以解决。
你的函数gameOver没有检查所有船只,因为返回语句:
if((ships[i].isDestroyed())){
return false; // LOOK HERE!!! :(
continue;
}
你必须检查所有的船都被摧毁了。
解决方案:
我将修改你的代码:
#include <algorithm> //for count_if()
bool islower(char a){
if( tolower(a) == a ) return true;
else return false;
}
bool Ship::isDestroyed() const{
// This is not necessary(You can let your isDestroyed function without any changes)
//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;
}
相关文章:
- 在分配器中销毁元素时,C++会导致双重释放<string>?
- 将 Vector<String > 元素复制到其他 Vector<String>* (1 作为
- 有没有办法搜索向量的元素,<String>然后检查它是否包含特定的字符,如果它确实打印了它
- 如何在一对集合的向量中插入元素?vector<pair<int,set<string>>>
- 如何将矢量元素复制到<string>字符串中?
- 如何检查 std::vector<std::string> 的元素是否以某个子字符串开头?
- 如何打印属于地图的一系列元素(std::p air<size_t,std::string>)(不是所有元素)
- 循环遍历向量<string>并保持每个元素"count"时出现问题
- 访问 std::string 中的元素,其中字符串的位置大于其大小
- 如何通过长度从 std::vector 中删除元素<string>(擦除不起作用)
- 为什么'std::string'中第一个元素的地址打印为整个字符串?
- 如何检查向量的第一个元素是否<string>是引号C++
- 字符串和向量<string>元素之间的区别
- unordered_map <(int 或 string),MyClass> 如何访问和打印 MyClass 的元素
- 获取列表的第一个和最后一个元素<string>给我非法指令错误
- C++向<string>量元素传递到函数会导致 SIGSEGV 崩溃
- 我可以在迭代 std::string 对象时删除它中的元素吗?
- 错误:非 POD 元素类型的可变长度数组'string'
- QStringList 的 PushBack (push_back()) 元素到向量<string>
- 在 vector<vector 中查找元素<string>>