Cast int or string to specific length, e.g. three digits …

Dear openFrameworkers,

for almost an hour I’m trying to cast an int or a string to a specific length, for example three digits (with leading zeros).

I don’t need int but string in my case, so maybe the conversion to int is not even necessary?

I tried the following, but it doesn’t work.

    for (auto xPos = 0; xPos < width; xPos++) {
        for (auto yPos = 0; yPos < height; yPos++) {
            auto color = ofToString(img.getColor(xPos, yPos));

            auto color_string = ofSplitString(color, ", ");

            auto color_int_r = ofToInt(color_string.at(0));
            auto color_int_g = ofToInt(color_string.at(1));
            auto color_int_b = ofToInt(color_string.at(2));

            auto x = ofToString(xPos % 100);
            auto y = ofToString(yPos % 100);

            auto r = ofToString(color_int_r % 100);
            auto g = ofToString(color_int_g % 100);
            auto b = ofToString(color_int_b % 100);

Thank you very much for your help!

PS: I need to store the leading zeros in the variables, I do not only need this conversion in my cout …

did you try this?

cout << ofToString(2, 4, '0');

second argument is the forced width, third is the char used to fill it up.

This works like a charm, thank you very much!

Though now I’m having these four lines, maybe they can be improved?

            auto c = ofSplitString(ofToString(img.getColor(xPos, yPos)), ", ");
            auto r = ofToString(c.at(0), 3, '0');
            auto g = ofToString(c.at(1), 3, '0');
            auto b = ofToString(c.at(2), 3, '0');

Because if adding the second and third argument to the first line, see below, I would only transform the first value to three digits it seems. Else this would be much nicer.

            auto c = ofSplitString(ofToString(img.getColor(xPos, yPos), 3, '0'), ", ");
            auto r = c.at(0);
            auto g = c.at(1);
            auto b = c.at(2);

Thank you!