2015-05-12 100 views
0

对于我的程序,我有一个高分区。我得到了一个字符串的输入,但我怎么现在使字符串等于一个字符数组?供参考:字符串playersName将已填写名称。这里是我的代码:C++使一个字符数组具有字符串的值

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

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

'name'是一个字符数组,因此它没有'size'方法:) – thelink2012

+0

@vsoftco,我已经解决了问题。 :) – ThatCoderBryan

+0

你的答案和下面的答案有什么区别?他们有吗? – ThatCoderBryan

1

你需要

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

@vsoftco我会这样说,'strcpy'可能易于缓冲溢出,主要是如果使用错误的begginers。我肯定地说你的答案是要走的路。 – thelink2012

+0

@ thelink2012我意识到现在,感谢您指出,我没有考虑溢出问题。仍然保持我的upvote虽然:) – vsoftco

相关问题