Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate 'consecutive' c++ strings?

Tags:

c++

string

random

I would like to generate consecutive C++ strings like e.g. in cameras: IMG001, IMG002 etc. being able to indicate the prefix and the string length.

I have found a solution where I can generate random strings from concrete character set: link

But I cannot find the thing I want to achieve.

like image 427
Patryk Avatar asked Dec 01 '25 08:12

Patryk


1 Answers

A possible solution:

#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>

std::string make_string(const std::string& a_prefix,
                        size_t a_suffix,
                        size_t a_max_length)
{
    std::ostringstream result;
    result << a_prefix <<
              std::setfill('0') <<
              std::setw(a_max_length - a_prefix.length()) <<
              a_suffix;
    return result.str();
}

int main()
{
    for (size_t i = 0; i < 100; i++)
    {
        std::cout << make_string("IMG", i, 6) << "\n";
    }
    return 0;
}

See online demo at http://ideone.com/HZWmtI.

like image 117
hmjd Avatar answered Dec 04 '25 01:12

hmjd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!