字符串转ASCII码:
时间: 2024-11-08 08:12:28 浏览: 3
Android字符串转Ascii码实例代码
在C++中,你可以使用`std::stringstream`或`std::bitset`来将字符串转换为ASCII码。这里是一个简单的例子,我们将逐个字符转换:
```cpp
#include <string>
#include <sstream>
#include <vector>
std::vector<unsigned char> string_to_ascii(const std::string& str) {
std::vector<unsigned char> ascii_codes;
for (char c : str) {
ascii_codes.push_back(c);
}
return ascii_codes;
}
int main() {
std::string input = "Hello, ASCII!";
std::vector<unsigned char> codes = string_to_ascii(input);
// Now you can iterate through the vector to see the ASCII values of each character
for (unsigned char code : codes) {
std::cout << static_cast<int>(code) << " ";
}
return 0;
}
```
在这个例子中,我们创建了一个`std::vector<unsigned char>`来存储ASCII值,然后遍历字符串中的每个字符,将其添加到这个数组中。
阅读全文