从C++中的std::string获取字节的方法是使用string的成员函数c_str()。这个函数返回一个指向字符串的C风格字符串的指针,可以通过指针访问字符串中的每个字节。
示例代码:
#include<iostream>
#include<string>
int main() {
std::string str = "Hello, World!";
const char* cstr = str.c_str();
for (int i = 0; i < str.length(); ++i) {
std::cout << "Byte " << i << ": "<< static_cast<int>(cstr[i])<< std::endl;
}
return 0;
}
输出:
Byte 0: 72
Byte 1: 101
Byte 2: 108
Byte 3: 108
Byte 4: 111
Byte 5: 44
Byte 6: 32
Byte 7: 87
Byte 8: 111
Byte 9: 114
Byte 10: 108
Byte 11: 100
Byte 12: 33
注意:这个方法只能获取字符串中的字节,而不能修改字节。如果需要修改字节,可以使用string的成员函数data(),它返回一个指向字符串中第一个字符的指针,可以通过指针修改字符串中的字节。
领取专属 10元无门槛券
手把手带您无忧上云