0

I'm trying to access the elements of a vector using this simple example:

#include <iostream>
#include <vector>

typedef std::vector<uint8_t> uint8_vec_t;

int main(void) {
    uint8_vec_t v = {1, 2, 3, 4};
    uint8_vec_t::iterator itr;
    std::cout << "v.size() = " << v.size() << std::endl;
    int i = 0;
    for ( itr = v.begin(); itr != v.end(); ++itr, i++) {
        std::cout << "std::cout: v[" << i << "] = " << v[i] << std::endl;
        std::cout << "std::cout: *itr =" << *itr << std::endl;
        printf("printf: v[%d] = %d\n", i, v[i]);
        printf("printf: *itr = %d\n", *itr);
    }
    //
    return 0;
}

And I get the following output:

v.size() = 4
std::cout: v[0] = 
std::cout: *itr =
printf: v[0] = 1
printf: *itr = 1
std::cout: v[1] = 
std::cout: *itr =
printf: v[1] = 2
printf: *itr = 2
std::cout: v[2] = 
std::cout: *itr =
printf: v[2] = 3
printf: *itr = 3
std::cout: v[3] = 
std::cout: *itr =
printf: v[3] = 4
printf: *itr = 4

I provide the same value to cout and printf but only printf prints the value to the terminal. Why cout doesn't print the value while I have no issue when using printf ?

Thanks for your help.

Paul R
  • 208,748
  • 37
  • 389
  • 560
vinczo
  • 21
  • 9
  • 1
    I'm sure there's a duplicate out there somewhere, but to sum it up `uint8_t` is most likely a type-alias for `unsigned char`, and all `char` (singed and unsigned) are printed as *characters*, and the ones you try to print are really unprintable as characters. Try casting the value to an `unsigned int`. – Some programmer dude Aug 29 '17 at 13:46
  • Found the solution. `std::cout` treats the `uint8_t` as `unsigned char`. I must cast `v[i]` or `*itr` to a numerical type : short, int, etc – vinczo Aug 29 '17 at 14:00
  • Thanks @Someprogrammerdude ! I will delete the post... – vinczo Aug 29 '17 at 14:01

0 Answers0