【发布时间】:2020-12-03 07:57:23
【问题描述】:
我需要检查我的向量是否包含所有空字符并根据该结果执行一些操作。我在 Stack Overflow 中发现了几个问题,但它们并不完全符合我的要求。
我能想到的决定一个全为空字符的向量的一种解决方案是:
if(Buffer[0] == '\0') {
std::cout<<"vector contains all NULL characters";
}
如果有更好的方法,请分享你的想法。
完整代码为:
文件1.cpp:
std::vector<unsigned char> Buffer(BufferSize, 0);
文件2.cpp:
try
{
// do some operation, if no exception then fill the buffer
// if exception then go to catch block
}
catch(...)
{
memset(Buffer, '\0', BufferSize);
}
在此之后,在 File1.cpp 中,我只得到 Buffer,其中填充了有效数据或 '\0'。
这是在 C++ 98 中
【问题讨论】:
-
您的第一个 sn-p 代码只检查第一个字符。为什么不用
clear()向量,或者使用std::optional<std::vector<unsigned char>>? -
不要对容器使用
memset,使用std::fill。 -
@Botje 由于来自其他文件的一些依赖关系,我不应该编辑该缓冲区
-
@LouisGo 我使用了
memset(),因为在 File2.cpp 中,缓冲区被视为unsigned char *