我需要使用一个std::string来存储检索到的数据fgets().要做到这一点,我需要将转换char*返回值从fgets()到std::string阵列中的存储.如何才能做到这一点?
我const char *从处理函数返回,我想将其转换/分配给std::string进一步操作的实例.这似乎应该是直截了当的,但我找不到任何文档说明应该如何完成.显然,我错过了一些东西.见解表示赞赏.
我想知道:char*cs = .....;如果cs指向内存块但是没有'\ 0',那么strlen()和printf("%s",cs)会发生什么?我写这些线:
char s2[3] = {'a','a','a'};
printf("str is %s,length is %d",s2,strlen(s2));
Run Code Online (Sandbox Code Playgroud)
我得到结果:"aaa","3",但我认为这个结果是因为'\ 0'(或0字节)恰好位于s2 + 3位置.如何制作一个非空终止的c字符串?strlen和其他c字符串函数严重依赖于'\ 0'字节,如果没有'\ 0',我只想更深入,更好地了解这条规则.
ps:通过研究SO上的帖子来激发我的好奇心. 如何将const char*转换为std :: string 以及该帖子中的这些单词:"这实际上比它看起来更棘手,因为除非字符串实际上是nul终止,否则你不能调用strlen."
以下函数返回一个 char*:
// Returns the pointer to the actual packet data.
// @param pkt_handle The buffer handle.
// @param queue The queue from which the packet is arrived or destined.
// @return The pointer on success, NULL otherwise.
u_char * pfring_zc_pkt_buff_data(
pfring_zc_pkt_buff *pkt_handle,
pfring_zc_queue *queue
);
Run Code Online (Sandbox Code Playgroud)
以下函数将字符串作为输入。
template<class ...Args>
bool write(Args&&... recordArgs) {
auto const currentWrite = writeIndex_.load(std::memory_order_relaxed);
auto nextRecord = currentWrite + 1;
if (nextRecord == size_) {
nextRecord = 0;
}
if (nextRecord != readIndex_.load(std::memory_order_acquire)) {
new (&records_[currentWrite]) …Run Code Online (Sandbox Code Playgroud)