0

I have a program that I compile on two Ubuntu computers. Both are running 14.04 and presumably the same version of gcc. But when I compile it on one computer, I get the error

warning: format ‘%i’ expects argument of type ‘int’, but argument 4 
has type ‘std::vector<colorgrad>::size_type {aka long unsigned int}’ [-Wformat=]

I think the offending code is

for (vector<colorgrad>::size_type i = 0; i < grad.size(); ++i) {

    fprintf(svgOut, "%s%i%s%f%srgb(%i, %i, %i)%s\n", "<stop id=\"stop", i,"\" offset=\"",grad.at(i).perc ,"\" style=\"stop-color: ",grad.at(i).r, grad.at(i).g, grad.at(i).b, ";stop-opacity:1;\" />" );

}

The error goes away when I replace the first "%i" with a "%lu" but then when I compile that code on the other computer, gcc gives the opposite error and will only compile with a "%i".

How do I get this code to compile on both computers without having to switch out the "%i"'s every time I switch computers??

Peter Gluck
  • 8,168
  • 1
  • 38
  • 37
kelvinsong
  • 218
  • 1
  • 7
  • 3
    Presumably one of your computers is running 64-bit Ubuntu, the other is running 32-bit. See [this question](http://stackoverflow.com/questions/1546789/clean-code-to-printf-size-t-in-c-or-nearest-equivalent-of-c99s-z-in-c). But as there's no great cross-platform story for that, also consider using iostreams instead of fprintf. – HostileFork says dont trust SE Jul 29 '14 at 00:35
  • 2
    Use `%zu` for `size_type`. – eduffy Jul 29 '14 at 00:36

1 Answers1

1

As mentionned in comment vector::size_t depend of the platform and may be 32 or 64 bits and the format %zu manage that.

Alternatively, you may write something like:
(I use C++11, for-range, Raw strings (to not have to escape \"), but it can also be done in C++03)

std::ofstream oss; // initialize it with correct value
std::size_t i = 0;
for (const auto& color : grad) {
    oss << R"(<stop id="stop)" << i << R"(" offset=")" << color.perc
        << R"(" style="stop-color: rgb()"
        << color.r << ", " << color.g << ", "<< color.b
        << R"();stop-opacity:1;" />)" "\n"; // you may replace "\n" by std::endl
    ++i;
}
Jarod42
  • 203,559
  • 14
  • 181
  • 302