skr
skr

Reputation: 944

C++ - A better way to create a null terminated c-style string of specific size with same character

I am looking to create a null terminated c-style string where every character is - (hyphen). I am using the following block of code:

char output_str[n + 1];
std::fill(output_str, output_str + n, '-');
output_str[n + 1] = '\0';

1) Is there a smarter C++ way to do this?

2) When I print the size of the string the output is n, not n + 1. Am I doing anything wrong or is null character never counted?

Edit:

Please consider this block of code instead of the one above:

char output_str[n + 1];
std::fill(output_str, output_str + n, '-');
output_str[n] = '\0';

And please ignore the question regarding size.

Upvotes: 0

Views: 327

Answers (2)

amchacon
amchacon

Reputation: 1961

1) Is there a smarter C++ way to do this?

Using the String class:

std::string output_str(n,'-');

In case you need a string in old C style

output_str.c_str(); // Returns a const char*

2) When I print the size of the string the output is n, not n + 1. Am I doing anything wrong or is null character never counted?

In your code, the N caracter is not added. If the array was pre-filled with zero, strlen function will return N.

Upvotes: 0

user0042
user0042

Reputation: 8018

Is there a smarter C++ way to do this?

Sure, use a std::string to do that:

std::string s(n,'-');
const char* cstyle = s.c_str();

Upvotes: 4

Related Questions