C 使char数组具有字符串的值
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
您可以使用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 `' '` at the end
data[playerScore].name[length] = ' ';
您需要
strcpy(data[playerScore].name, playersName.c_str());