strcpy 复制另一个数组的内容
strcpy copies content of an other array
所以我有这段代码可以将 char 数组转换为结构的内容。 (不,我不会争论这是否是 right/most 有效的方法)
void chararray_to_categorie(categorie &levarr, char** chararray)
{
string temp = chararray[0];
int length = temp.length();
temp = temp.substr(0, ((length<21)?length:20));
strcpy(levarr.naam, temp.c_str()); //a very sloppy way to use substring on a char array. Tried memcpy and that caused the same results which is why I'm trying it this way.
levarr.naam[20] = '[=10=]';
strcpy(levarr.omschrijving, chararray[1]);
cout << endl << chararray[0] << endl << temp << endl << levarr.naam << endl << length << endl << ((length<21) ? length : 20);
_getch();
/*
input:
naam: 1234567890123456789012345678901234567890
omschrijving: lol
output:
chararray[0]: 1234567890123456789012345678901234567890
temp: 12345678901234567890
levarr.naam: 12345678901234567890lol
*/
}
正如您在输出中看到的那样,您可以看到结构的内容组合了 2 个字符数组,这就是问题所在。
您的代码中有很多地方不是最理想的,但错误归结为:
levarr.naam[20] = '[=10=]';
应该是
levarr.naam[19] = '[=11=]';
因为数组是从 0 开始计数的;
其他需要解决的问题:
- 使用以 NULL 结尾的字符串并具有大小参数的保存
strcpy
函数,它可以防止您遇到此问题。
- 不要获取子字符串,使用安全函数仅从原始字符串中复制那么多字符。
所以我有这段代码可以将 char 数组转换为结构的内容。 (不,我不会争论这是否是 right/most 有效的方法)
void chararray_to_categorie(categorie &levarr, char** chararray)
{
string temp = chararray[0];
int length = temp.length();
temp = temp.substr(0, ((length<21)?length:20));
strcpy(levarr.naam, temp.c_str()); //a very sloppy way to use substring on a char array. Tried memcpy and that caused the same results which is why I'm trying it this way.
levarr.naam[20] = '[=10=]';
strcpy(levarr.omschrijving, chararray[1]);
cout << endl << chararray[0] << endl << temp << endl << levarr.naam << endl << length << endl << ((length<21) ? length : 20);
_getch();
/*
input:
naam: 1234567890123456789012345678901234567890
omschrijving: lol
output:
chararray[0]: 1234567890123456789012345678901234567890
temp: 12345678901234567890
levarr.naam: 12345678901234567890lol
*/
}
正如您在输出中看到的那样,您可以看到结构的内容组合了 2 个字符数组,这就是问题所在。
您的代码中有很多地方不是最理想的,但错误归结为:
levarr.naam[20] = '[=10=]';
应该是
levarr.naam[19] = '[=11=]';
因为数组是从 0 开始计数的;
其他需要解决的问题:
- 使用以 NULL 结尾的字符串并具有大小参数的保存
strcpy
函数,它可以防止您遇到此问题。 - 不要获取子字符串,使用安全函数仅从原始字符串中复制那么多字符。