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

标签 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

最佳答案

您可以使用 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/

相关文章:

c++ - 模板类可选地插入初始值作为模板参数

javascript - 如何拆分和添加字符串中的各个值?

c++ - 在排序和旋转的数组中搜索

Java 数据库显示国家数据库表中的所有国家信息

php - 动态调用一个静态变量(数组)

c# - 如何查找/比较 List<class> 中的类属性

c++ - 我怎样才能跳过这些警告? C++

c++ - (C++) 游戏服务器、(Flash) 客户端

c++ - 我应该符号链接(symbolic link) C++ 包含目录,以便它也出现在/usr/include 下吗?

php - 如何按长度对字符串数组进行排序并在 PHP 中维护它们的键?