【问题标题】:C++ Make a Char Array have a Value of the stringC ++使字符数组具有字符串的值
【发布时间】:2015-05-12 02:37:23
【问题描述】:

对于我的程序,我有一个高分部分。我得到了一个字符串的输入,但是我现在怎样才能使这个字符串等于一个 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

【问题讨论】:

    标签: c++ arrays class char


    【解决方案1】:

    你可以使用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';
    

    【讨论】:

    • name 是一个字符数组,所以它没有size 方法:)
    • 你的答案和下面的有什么区别?他们有吗?
    • 另外,我认为.copy 的第二个参数应该是它可以复制到name 的最大数量(即sizeof(name)
    • @ThatCoderBryan 这种方法更安全,因为它避免了name的溢出,从而避免了安全漏洞。
    • 最后的'\0'做了什么?
    【解决方案2】:

    你需要

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

    【讨论】:

    • @vsoftco 我不会这么说,strcpy 可能容易出现缓冲区溢出,主要是初学者错误地使用。我肯定地说你的答案是要走的路。
    • @thelink2012 我现在意识到,感谢您指出,我并没有考虑溢出问题。不过仍然保持我的赞成票:)
    猜你喜欢
    • 1970-01-01
    • 2012-05-24
    • 2020-03-30
    • 2015-09-08
    • 2020-12-01
    • 1970-01-01
    • 2018-09-01
    • 1970-01-01
    • 2014-10-18
    相关资源
    最近更新 更多