Search code examples
c++stringstreamzero-pad

Keeping zero padding in stringstream


I have a memory area containing characters that represent different hex words. When I print them I would like to keep all characters but with my current code zero padding in non-zero numbers is stripped off. For example if I have in memory characters 0000 it outputs 0000 but if I have 0001 it outputs 1. I am currently using a stringstream, but have also tried using a character array to construct a string (see comments):

stringstream ss;
char* data_ptr = sets[set_index]->get_block(block_index)->get_word(word_index);
for (int d = 0; d < 2 * bytes_word; d++){
    ss << *(data_ptr + d);
}
data = ss.str();

//char* data_ch = new char[2 * bytes_word];
//char* data_ptr = sets[set_index]->get_block(block_index)->get_word(word_index);
//for (int d = 0; d < 2 * bytes_word; d++){
//  data_ch[d] = *(data_ptr + d);
//}
//string data(data_ch);
//delete[] data_ch;

From this I tend to thing that the stripping might actually be done when I pass the string to the stdout, I use cout << data;, since my debug mode shows the contents of the string in both cases to contain all 0's. If this is so how could I solve it?

EDIT - Solved As posted in accepted answer had to used setfill() and setw() which I wasnt aware of. This didnt solve the problem at first because data_ptrpoints to characters, I simply took out the for loop and used atoi(data_ptr)


Solution

  • Try using

     std::cout << std::setfill('0') << std::setw(4) << data;
    

    Cheers!