c++如何将大字符串放入固定字符数组
c++ how to put large string into fixed char array
嘿,我有一个很长的字符串,我试图把它粘在一个固定大小的字符数组。我不在乎字符串是否被截断,我只希望字符数组的每个元素都有一些东西。
例如char first_ten_alaphabet[10];
string str = "abcdefghijklnopqrstuvwxyz";
strcpy(first_ten_alaphabet, str.c_str()); //<-- this will cause program to break
任何帮助都很好,谢谢
如果你想复制(并可能截断)一个c风格的字符串,那么我会使用strncpy而不是"strcpy()"。
strncpy()的一个限制是,如果#/字符正好等于复制长度,它将而不是以null终止字符串。这是设计的结果,但如果你没有预料到,这是一个潜在的"陷阱"。只需添加第二个语句,在最后位置放置一个NULL字符:
char first_ten_alphabet[10];
string str = "abcdefghijklnopqrstuvwxyz";
strncpy(first_ten_alphabet, str.c_str(), sizeof(first_ten_alphabet));
first_ten_alphabet[sizeof(first_ten_alphabet)-1] = ' ';
use std:copy,http://www.cplusplus.com/reference/algorithm/copy/copy(str.begin(),str.begin()+sizeof(first_ten_alaphabet),first_ten_alaphabet);
相关文章:
- 指向指向字符数组的指针数组的指针
- 比较字符数组
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 使用无符号字符数组有效存储内存
- 错误:字符数组的初始值设定项太多
- 对字符数组中的元素执行逐位操作
- C++ 无法在字符数组中使用 for 循环打印字母模式
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- C++ 传递二维字符数组
- 无法在 C++ 中输入字符数组
- 字符数组中的元素数
- 我的目标是编写一个程序来计算和存储字符串在字符数组中出现的位置
- 使用字符数组作为 Map 中的键
- C++:__aligned(__alignof__) 导致字符数组数据出现问题?
- 按顺序声明的字符数组重叠
- 在 C++ 中字符串的大小与字符数组的大小
- 寻找一种更好的方法来表示无符号字符数组
- 如何打印 2D 字符数组C++
- 从字符数组的元素中减去'a'是什么意思
- 我是否不正确地集中了这些字符数组?