Is there a quick way to do the following without the repetition of i++
int i = 0;
printf("foo-%d,blah-%d,orange-%d", i++, i++, i++);
I need to do this with 8 or more pairs and the code looks horrible..
Is there a quick way to do the following without the repetition of i++
int i = 0;
printf("foo-%d,blah-%d,orange-%d", i++, i++, i++);
I need to do this with 8 or more pairs and the code looks horrible..
The order of evaluation of arguments is unspecified. Also, you can't modify a variable twice without an intervening sequence point. So do this instead:
printf("foo-%d,blah-%d,orange-%d", i, i+1, i+2);
i+=3;
Since you can have 8 or more pairs, I would like to suggest you to use a more readably and easy to extend version:
std::vector<std::string> vec_values = {"foo", "blah", "orange"};
for (size_t index = 0; index < vec_values.size(); ++index)
std::cout << vec_values[index] << "-" << index;
You might think of it in terms of the prefixes, not of the number:
int i = 0;
std::vector<std::string> prefixes { "foo", "bar", "baz", "ham" };
bool first = false;
for (const auto& prefix : prefixes) {
if (!first)
std::cout << ',';
std::cout << prefix << '-' << i++;
first = false;
}
If you can’t use C++11 range-based for
, you can write it out in full:
for (auto prefix = prefixes.begin(); prefix != prefixes.end(); ++prefix) {
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if (!first)
std::cout << ',';
std::cout << *prefix << '-' << i++;
// ~~~~~~~
first = false;
}
Alternatively, use indices:
for (i = 0; i < prefixes.size(); ++i) {
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if (!first)
std::cout << ',';
std::cout << prefixes[i] << '-' << i;
// ~~~~~~~~~~~ ~
first = false;
}