查找char数组的长度

时间:2013-11-06 11:07:01

标签: c++ arrays string char codeblocks

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

提前致谢!

5 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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();

答案 2 :(得分:1)

使用std :: string

的.size()方法

答案 3 :(得分:0)

我认为标准模板库(STL)对您来说非常有用。 特别是std :: vectors。向量不需要您想要放入的字符串长度。 您可以使用ITERATORS在矢量中导航。

答案 4 :(得分:-1)

可以通过sizeof找到生成的单词的长度。

int length = sizeof(word);

回答: Finding length of char array