簡體   English   中英

將字符串從2d char array C ++分配給char array

[英]Assign string to char array from 2d char array c++

我正在嘗試找到一種從2d char數組中隨機選擇一個單詞並將其放入另一個char數組中的方法。 這是我的代碼:

    char wordbank[5][20] = {"house", "car", "tree", "bicycle", "shark"};
    int random = rand() % 5;
    char word[20] = wordbank[random];

我在最后一行顯示編譯器錯誤:數組必須用大括號括起來的初始化程序進行初始化。 這樣做的正確方法是什么?

要回答您的問題:

char* word = wordbook[random];

附帶說明:生成隨機數的方式存在嚴重問題。 您如何保證random永遠不會大於4?

由於嘗試將char *分配給chars數組,因此出現了編譯錯誤。

由於wordbank是2D數組,因此wordbank [index]將為char *(指向char的指針)。 C和C ++沒有從char *到char數組的隱式轉換。 因此,您將得到一個編譯錯誤。

如果要在字庫中復制隨機字符串,可以這樣進行:

char wordbank[5][20] = {"house", "car", "tree", "bicycle", "shark"};
srand (time(NULL));
int random = rand() % 5;
char word[20];
strcpy(word, wordbank[random]); // strcpy (string copy) takes a copy of the 2nd string
                                // (i.e. wordbank[random]) and puts it into the 1st 
                                // string (i.e. word).

如果您只想指向wordbank中的隨機字符串,可以這樣進行:

char wordbank[5][20] = {"house", "car", "tree", "bicycle", "shark"};
srand (time(NULL));
int random = rand() % 5;
char* word = wordbank[random]; // word is a pointer to a string. It is
                               // initialized to point to the string
                               // held by wordbank[random]

使用第一種方法,您可以更改單詞的值而無需更改單詞庫的值。 使用第二種方法,您將同時更改兩者。

順便說一句-使用std :: string代替C風格的字符串,使用vector代替array。 如果您真的想要一個數組,請改用C ++樣式。

就像是:

vector<string> wordbank;          // Make a vector of strings to hold your wordbank
wordbank.push_back("house");      // Add words to wordbank one-by-one
wordbank.push_back("car");        // ...
wordbank.push_back("tree");       // ...
wordbank.push_back("bicycle");    // ...
wordbank.push_back("shark");      // ...
                   // or add all words at initialization - like:
                   //vector<string> wordbank {"house", "car", "tree", "bicycle", "shark"};

srand (time(NULL));
int random = rand() % wordbank.size();
string word = wordbank[random];   // Copy wordbank[random] into word

現在,您可以將新單詞添加到單詞庫中,而無需計算它包含多少個單詞以及單個單詞的持續時間。

如果可以使用C ++ 11,則至少應使用std::array ,但可能應使用std::vector 然后你可以使用這個功能

#include <random>
#include <stdexcept>
#include <cstddef>
#include <iterator>

template <typename Container>
typename Container::value_type random_member(const Container& values)
{
    static std::default_random_engine generator {};
    if (values.empty()) throw std::runtime_error {"cannot sample from empty container"};
    std::uniform_int_distribution<size_t> distribution {0, values.size() - 1};
    return *std::next(std::cbegin(values), distribution(generator));
}

以下是按理智的順序使用它的方法:

#include <iostream>
#include <array>
#include <string>
#include <vector>

int main()
{
    std::array<const char*, 5> wordbank {"house", "car", "tree", "bicycle", "shark"};
    std::cout << random_member(wordbank) << std::endl;

    std::array<std::string, 5> a {"house", "car", "tree", "bicycle", "shark"};
    std::cout << random_member(a) << std::endl;

    std::vector<std::string> v {"house", "car", "tree", "bicycle", "shark"};
    std::cout << random_member(v) << std::endl;

    return 0;
}

char數組可以通過括號初始化程序或字符串文字構造。

這是初始化數組的兩種方法:

    char someSequence[5] = {'a','b','c','d','e'}
    char someWord[] = "Hello";

兩種初始化方法都可以使用顯式表示的大小,也可以不使用。

您不能使用char *指針初始化靜態數組。

這是獲得相同錯誤的另一種方法:

   char* someArray =new char[40];
   char someStaticArray[40] = someArray; // notice the same compile error ?

這行在語法上是錯誤的。 您不能像下面這樣初始化數組。

char word[20] = wordbank[random];

如果要在定義數組時初始化數組,則必須使用大括號括起來的{}或“”(const string Ex:“ Hello”)。

在你的問題上

代替使用一維數組,使用字符指針從二維數組字庫中獲取單詞。

此代碼段可能會對您有所幫助。 但是,請嘗試改善您的問題。 它會給你更好的答案

int main()
{
     char wordbank[5][20] = {"house", "car", "tree", "bicycle", "shark"};
     int random = (rand() % 5);
     char *word = wordbank[random];
     cout << word;
}
const int size = 5;
const char * wordbank[size] = 
{"house", "car", "tree", "bicycle", "shark"};

const char * word = wordbank[ rand() % size ];

大小是字符串數。 Wordbank是一個字符串數組,其大小為5。word是一個字符串,它是隨機索引的結果。 索引由函數rand給出,該函數的范圍為0-4,因此沒有超出范圍。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM