3

I can format an Int to display a number with leading zeros, but I can't figure out how to save an Int with the zeros to a string.

Reason: Loading image files that end in "..0001" "..0002" ... "..0059" etc.

I have this, but it doesn't work:

int a;
for(int i = 1; i < imgArraySize + 1; i++)
{
    cout << setw(4) << setfill('0') << i << '\n';
    cin >> a;
    string aValue = to_string(a);

    imageNames.push_back(string("test_images" + aValue + ".jpg"));
}
MLMLTL
  • 1,519
  • 5
  • 21
  • 35
  • possible duplicate of [Convert a number to a string with specified length in C++](http://stackoverflow.com/questions/225362/convert-a-number-to-a-string-with-specified-length-in-c) – Cory Kramer Oct 21 '14 at 12:14

1 Answers1

4

You can apply the same formatting with a stringstream

std::ostringstream ss;
ss << std::setw(4) << std::setfill('0') << a;
std::string str = ss.str();
std::cout << str;

Live example

Marco A.
  • 43,032
  • 26
  • 132
  • 246