带有额外 0x0 的 C++ 字符串?

标签 c++

我有一个奇怪的带有 0x0 的字符串,有人可以帮我吗?

string a = funxx();  // funxx is a external func from Crypto++ libary
string b = "test"

如果我打印出a和b的内容,它们都显示为“test”

a.size() is: 5
b.size() is: 4
a.length() is: 5
b.length() is: 4

for( int i = 0; i < a.size(); i++ ) {
    cout << "0x" << hex << (0xFF & static_cast<byte>(a[i])) << " ";
}
print out: 0x74 0x65 0x73 0x74 0x0

for( int i = 0; i < b.size(); i++ ) {
    cout << "0x" << hex << (0xFF & static_cast<byte>(b[i])) << " ";
}
print out: 0x74 0x65 0x73 0x74

我的问题是,为什么 a.length()a.size() 返回 5 而不是 4,如何让ab相等?

总结: 感谢您的大量回复。我认为现在问题对我来说很清楚了。来自 Crypto++ 库的外部 func 在字符串中返回一个额外的空字符,并且在字符串中,长度被单独跟踪。 我需要做的是 std::string(a.c_str())

最佳答案

std::string 中删除尾随 null 的简单方法:

if (!str.empty() && *str.rbegin() == 0)
    str.resize(str.size() - 1);

关于带有额外 0x0 的 C++ 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25049844/

相关文章:

c++ - OpenCV 检测项目的多个实例

c++ - GetQueuedCompletionStatusEx() 不返回 per-OVERLAPPED 错误代码

c++ - 我应该如何使用 mpfr::mpfr_fac_ui 函数?

c++ - 这些数组类型有何不同?

c++ - 字符串/数组情况 c++

c++ - 画一个连续的螺旋?

c++ - 分配器如何创建和销毁数组?

C++ 管理器对象和虚函数

c++ - 将字符串写入指针 C++

C++ 无法识别 DLL 中的命令