Home > Mobile >  Build incremental std::string
Build incremental std::string

Time:12-15

I try to build an std::string in the form of "start:Pdc1;Pdc2;Pdc3;" With following code I can build the repeated "Pdc" and the incremental string "123" but I'm unable to combine the two strings.

#include <string>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <iterator>
#include <numeric>

int main()
{
    std::ostringstream ss;
    std::string hdr("start:");
    std::fill_n(std::ostream_iterator<std::string>(ss), 3, "Pdc;");
    hdr.append(ss.str());

    std::string v("abc");
    std::iota(v.begin(), v.end(), '1');

    std::cout << hdr << std::endl;
    std::cout << v << std::endl;

    std::cout << "Expected output: start:Pdc1;Pdc2;Pdc3;" << std::endl;

    return 0;
}

How can I build this string? Preferable without a while or for loop.
The expected output is: start:Pdc1;Pdc2;Pdc3;

CodePudding user response:

std::strings can be concatenated via their operator (or =) and integers can be converted via std::to_string:

std::string res("start:");

for (int i=0;i<3;  i){
    res  = "Pdc"   std::to_string(i 1)   ";";
}
std::cout << res << "\n";

If you like you can use an algorithm instead of the handwritten loop, but it will still be a loop (your code has 2 loops, but only 1 is needed).

CodePudding user response:

Code to generate your expected string, though with a small for loop.

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

std::string cmd(const std::size_t N)
{
    std::ostringstream os;
    os << "start:";
    for(std::size_t n = 1; n <= N;   n) os << "Pdc" << n << ";";
    return os.str();
}

int main()
{
    std::cout << cmd(3ul);
    return 0;
}
  •  Tags:  
  • c
  • Related