查找字符数组的长度
Find length of char array
我正在用Code::Blocks创建一个基于文本的刽子手游戏(C++显然;))。
所以我创建了一个数组 char knownLetters[]; 但我不知道这个词会有多长,我怎么能计算字符串中会有多少个字符?
法典:
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
string GenerateWord() // Generate random word to be used.
{
srand(time(NULL));
int wordID = rand() % 21;
string wordList[20] = {"Dog" ,"Cat","Lion","Ant","Cheetah","Alpaca","Dinosaur","Anteater","Shark","Fish","Worm","Lizard","Bee","Bird","Giraffe","Deer","Crocodile","Wife","Alligator","Yeti"};
string word = wordList[wordID];
return word;
}
void PrintLetters() // Display the word including underscores
{
string word = "";
char knownLetters[word];
for(int pos = 0; pos < word.length(); pos++) {
if(knownLetters[pos] == word[pos]) cout << word[pos];
else cout << "_";
}
cout << "n";
}
void PrintMan() // Display the Hangman to the User
{
// To Be completed
}
void PlayerLose() // Check For Player Loss
{
// To Be completed
}
void PlayerWin() // Check For Player Win
{
// To Be completed
}
int main()
{
cout << "Hello world!" << endl;
return 0;
}
提前感谢!
从生成的随机字符串中,您可以使用 size
方法查找其大小
http://www.cplusplus.com/reference/string/string/size/
然后,这可以用于数组的大小,或者更好地使用向量,然后您无需担心大小
void PrintLetters(const std::string& word) // Pass the word in here
{
const int size = word.size();
如果它是一个基于 C 字符的字符串,则可以使用 strlen。但是,字符串必须以 \0 结尾。
使用 std::string 的 .size() 方法
我认为标准模板库(STL)在这里对您非常有用。特别是标准::向量。向量不需要要放入的字符串长度。您可以使用迭代器在矢量内导航。
可以通过 sizeof 找到生成的单词的长度。
即
int length = sizeof(word);
回答来自:查找字符数组的长度
相关文章:
- 指向指向字符数组的指针数组的指针
- 比较字符数组
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 使用无符号字符数组有效存储内存
- 按字符值访问int数组
- 错误:字符数组的初始值设定项太多
- 对字符数组中的元素执行逐位操作
- C++,在int数组中输入字符串或字符会输出0,而不是ascii或error
- C++ 无法在字符数组中使用 for 循环打印字母模式
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- 移动二维数组中的字符
- C++ 传递二维字符数组
- 无法在 C++ 中输入字符数组
- C++ 带结构的数组字符
- 数组字符包含量超出预期
- 读取文件并添加到数组字符
- 如何在Qt中更改或替换数组字符
- 为什么编译器不在参数中传递数组字符 *arr[] 的大小?
- 井字棋数组字符错误
- 分割数组字符