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

时间:2015-05-12 02:37:23

标签: c++ arrays class char

对于我的节目,我有一个高分的部分。我用字符串获取输入,但是我现在如何使字符串等于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

2 个答案:

答案 0 :(得分:2)

您可以使用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 `'\0'` at the end
data[playerScore].name[length] = '\0';

答案 1 :(得分:1)

你需要

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