查找字符数组的长度

Find length of char array

本文关键字:数组 字符 查找      更新时间:2023-10-16

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

回答来自:查找字符数组的长度