s.n
s.n

Reputation: 703

I am trying to understand the line with string declaration

string Possible::str(int width) const {
    string s(width, ' '); // <-- this line
    int k = 0;
    for (int i = 1; i <= 9; i++) {
        if (is_on(i)) s[k++] = '0' + i;
    }
    return s;
}

What does that mean? string s(width, ' ');

Upvotes: 1

Views: 49

Answers (3)

Mo Abdul-Hameed
Mo Abdul-Hameed

Reputation: 6110

It means that the (space) character will be repeated (width) times.

So for example if width is 5, the output of this line will be 5 spaces.

Check this example about using std::string constructors.

Upvotes: 3

AnT stands with Russia
AnT stands with Russia

Reputation: 320361

That line declares and defines object s of type string and specifies (width, ' ') as an initializer for that new object. This initializer will result in a corresponding string's constructor with two parameters being invoked. That constructor will initialize object s.

If string is actually std::string, then this will invoke string::string(size_t n, char c) constructor. It will initialize s with a string of length width consisting entirely of space characters.

Upvotes: 1

Thomas Matthews
Thomas Matthews

Reputation: 57678

Its one of the std::string constructors, for building a string of repeat characters.

Upvotes: 3

Related Questions