put zeros in front of vector elements

hi everyone!

i'm trying to find a solution to the following problem:

i converted chars into int. for example char 'a' becomes int '97' (using ascii). then i saved those integers in a vector. no problem so far.

what i'm trying to do now is to get 3 digits for every vector element. for example 'a' becomes '097'. so i'm trying to put zeros in front of elements that only have 1 or 2 digits.

any suggestions?

thanks
The <iomanip> header as a setfill function that may meet your needs:
http://www.cplusplus.com/reference/iostream/manipulators/setfill/

That is, if by "get 3 digits" you mean print 3 digits for every vector element. If you want to somehow have the leading zeroes stored in the variable, then you will have to store the ints as std::strings for example.
As per the previous poster the leading 0 means nothing on a numeric value. if you want a vector of 3 character strings:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <sstream>
#include <string>
#include <vector>

template <typename VAL> std::string to_string(VAL V)
  {
    std::stringstream ss;
    ss << V;
    return ss.str();
  }

std::vector<int> numbers; // we'll assume this is filled with numbers from 0 - 255 since you want 3 digits
std::vector<std::string> numberStrings;

...

for(std::vector<int>::iterator idx = numbers.begin(); idx != numbers.end(); ++idx)
{
  std::string num;
  if(*idx < 10) num = "00";
  else if(*idx < 100) num = "0";
  num += to_string(*idx);
  numberStrings.push_back(num);
}
Last edited on
thanks so far.

my actual problem is encoding a word (for example the word "code") into numbers (so that "code" becomes "099 111 100 101"). later i want to reconstruct the word out of the safed number (in this case 099 111 100 101).

my plan was to assign 3 digits to every character in order to avoid mixing up the characters. normally i would store every character as a vector element, but i need to operate with the whole "code number".

by the way the project i'm working on is secret sharing based on the chinese remainder theorem.
but i need to operate with the whole "code number"

You can store the whole code as a vector of strings (or alternatively as one string). To reconstruct the original word, you can convert each string (or group of three characters) back to numeric (the <sstream> header can help you with this) and then from numeric back to the character.
Last edited on
ok thanks. i'll have a look.
Topic archived. No new replies allowed.