Search code examples
c++stringintleading-zero

c++ Save Int with leading zeros to String, NOT displaying them


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"));
}

Solution

  • 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