2

I want to build a string label with a changing suffix. This is to take place within a for-loop. (The suffix being the value that is looped through). This is how I'd do it in C - is there a more c++-ish way to do this?

for (int i = 0; i<10; i++)
{
    char label[256];

    sprintf(label, "Label_no_%d", i);

    // convert label to a c plus plus string

    // Do stuff with the string here
}
between
  • 185
  • 1
  • 5

5 Answers5

7

You can use stringstreams:

for (int i = 0; i<10; i++)
{
    std::ostringstream label;

    label << "Label_no_" << i;

    // use label.str() to get the string it built
}

These let you use operator<<, exactly like you would for std::cout or a file, but writing to an in memory string instead.

Or alternatively you can use Boost.Format, which behaves more like sprintf with a C++ interface.

Community
  • 1
  • 1
Flexo
  • 84,884
  • 22
  • 182
  • 268
3

Use stringstream :-

#include <sstream>
#include <string>

for (int i = 0; i<10; i++)
{
    std::ostringstream ss;
    ss << "Label_no" << i; 

    std::string label = ss.str();
}
jcoder
  • 28,803
  • 18
  • 83
  • 127
2

You can also use boost::lexical_cast

std::string label = "Label_no_" + boost::lexical_cast<std::string>(i);
rve
  • 5,643
  • 3
  • 38
  • 64
2

There's std::to_string() for converting a numeric value to a string. (C++11)

NFRCR
  • 4,904
  • 5
  • 31
  • 36
1

The code says it all. Use ostringstream from the <sstream> header—it’s an ostream backed by a string buffer. It’s not as efficient as sprintf() because of the dynamic allocation, but that won’t matter unless this is in a hot part of the program, and using stringstream is worth it for the safety.

#include <sstream>

for (int i = 0; i<10; i++) {

    std::ostringstream label;
    label << "Label_no_" << i;

    use(label.str());

}
Jon Purdy
  • 51,678
  • 7
  • 93
  • 161