我在将定义长度的字符序列数组存储到结构对象时遇到问题。我可以在不定义字符长度或仅使用字符串的情况下使其工作,但它只是困扰我为什么会发生这种情况。
代码:
#include <iostream>
#include <string>
using namespace std;
struct highscore {
char name[50];
int score;
char date[10];
} hstable[9];
void printtable (highscore show_tab) {
cout << show_tab.name << show_tab.score << show_tab.date;
};
void main() {
hstable[0].name = "Kyle ";
hstable[0].score = 100;
hstable[0].date = " 01/03/88 \n";
printtable (hstable[0]);
system("pause");
return;
};
错误:
错误 C2440:“=”:无法从“const char [6]”转换为“char [50]” 1> 没有可以进行这种转换的上下文
错误 C2440:“=”:无法从“const char [12]”转换为“char [10]”
最佳答案
如果你想这样做,你应该使用 strcpy
(或 strncpy
)来自 <cstring>
的函数标题。
strcpy(hstable[0].name, "Kyle ");
但请考虑使用 std::string
而不是普通的 char 数组。
备注:char[10]
太小无法存放" 01/03/88 \n"
作为 C 字符串,所以您已经落入了 C
的众多陷阱之一。字符串提供(在这种情况下缓冲区溢出)。
关于c++ - 字符数组顺序错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6889998/