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
  • 215
  • 2
  • 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
  • 87,323
  • 22
  • 191
  • 272
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
  • 29,554
  • 19
  • 87
  • 130
2

You can also use boost::lexical_cast

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

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

NFRCR
  • 5,304
  • 6
  • 32
  • 37
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
  • 53,300
  • 8
  • 96
  • 166