如何正确打印无符号字符向量的一部分

How to print a part of a vector of unsigned chars properly?

本文关键字:向量 一部分 字符 无符号 何正确 打印      更新时间:2023-10-16
typedef unsigned char BYTE;
std::vector<BYTE> bytes = readFile(path.c_str());

假设我想在向量中从位置30打印到34。

i tried this:

unsigned char chars[4];
for (int i = 30; i < 34; i++)
{
    chars[i-30] = bytes[i];
}
std::cout << chars << std::endl;

我得到一个奇怪的符号,就是这样。从30到34的字符向量包含x14, 。我尝试将字符转换为unsigned int,以及一些类似的东西。

如果你只写std::cout << chars << std::endl,它当然会打印出奇怪的东西,因为chars是一个指针。它在它的地址和下面的位置打印这个值,直到它到达的值读到。在你的chars数组上做一个循环来打印它的内容,而不是直接打印它。如果您希望输出格式正确,也可以将其转换为int类型:

for (int i = 0; i < 4; i++) {
    std::cout << static_cast<unsigned int>(chars[i]) << std::flush;
}

您也可以使用这个(是的,它会跳过''):

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef unsigned char BYTE;
struct printer{
    void operator()(BYTE c){
        if(c != 0){
            cout << c;
        }
    }
} printer;
int main() {
    vector<BYTE> v ={'a', '' ,'b', '', 'c', 'D'};
    BYTE a[6] = {'h', '', 'i', '', 'o', 'p'};
    for_each (v.begin(), v.end(), printer);
    cout<<endl <<"Now array" << endl;
    for_each (a, a + 6, printer);
    return 0;
}