Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Is there a way to create a string of say 256 characters at initialization with c++?

Part of my assignment requires me to "1. Create a string of 256 characters. Use repetitions of your first name."

I'm not quite sure of how to do this other than using a loop but I feel like there is an easier way.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
219 views
Welcome To Ask or Share your Answers For Others

1 Answer

Taking a look at the constructor reference of basic_string, one can see that there is no easy way of repeating a complete string. For a single character, you could use (2) like this:

std::string s(5, 'a'); // s == "aaaaa"

For generating a string repetition, you'll need some workaround. It's easier to do this post-construction by simply filling the string with, for example, std::generate (having fun with algorithms).

#include <string>
#include <algorithm>

// ...

std::string pattern("Xeo ");
auto pattern_it = pattern.begin();
std::string s(256, '');
std::generate(s.begin(), s.end(),
    [&]() -> char { 
      if(pattern_it == pattern.end())
        pattern_it = pattern.begin();
      return *pattern_it++; // return current value and increment
    });

Live example.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...