对于我的程序,我有一个高分部分。我得到了一个字符串输入,但是现在我怎样才能使这个字符串等于一个 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 `'\0'` at the end
data[playerScore].name[length] = '\0';
关于C++使一个字符数组具有字符串的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30180823/