-2

我正在 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;
}

提前致谢!

4

5 回答 5

1

如果它是基于 C 字符的字符串,则可以使用strlen。但是,字符串必须以 \0 结尾。

于 2013-11-06T11:11:38.440 回答
1

从生成的随机字符串中,您使用该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();
于 2013-11-06T11:18:17.507 回答
1

使用 std::string 的 .size() 方法

于 2013-11-06T11:34:50.253 回答
0

我认为标准模板库(STL)在这里对你很有用。特别是 std::vectors。向量不需要您要输入的字符串的长度。您可以使用迭代器在向量内导航。

于 2013-11-06T11:13:23.693 回答
-1

可以通过sizeof求出生成词的长度。

IE

int length = sizeof(word);

答案来自: 查找 char 数组的长度

于 2013-11-06T11:20:34.573 回答