C ++使一个字符数组具有字符串的值

C++ Make a Char Array have a Value of the string

对于我的程序,我有一个高分部分。我得到了一个字符串输入,但是现在我怎样才能使这个字符串等于一个 char 数组呢?仅供参考:字符串 playersName 已经填写了名称。这是我的代码:

class Highscore
{
    public:
        char name[10];
        ...[Code]...
}

...[Code]...
// Declare variables *The playersName will be filled out already*
string playersName = "";
...[Code]...

// How can I get the data[playerScore].name equal my playersName string?
cin.get (data[playerScore].name, 9);
// I know cin.get will be not in the code since I already get the players name with the string

你需要

strcpy(data[playerScore].name, playersName.c_str());

可以使用std::string::copy成员函数,比如

// length of the destination buffer so we won't overflow
size_t length = sizeof data[playerScore].name; 

// copy the string content to the char buffer
playersName.copy(data[playerScore].name, length);

// add the `'[=10=]'` at the end
data[playerScore].name[length] = '[=10=]';