0

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.

skr_robo
  • 770
  • 13
  • 31

2 Answers2

4

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();
user0042
  • 7,691
  • 3
  • 20
  • 37
  • 1
    As a bonus, some (but not all) implementations use the [Small String Optimization / SSO](https://stackoverflow.com/questions/10315041/meaning-of-acronym-sso-in-the-context-of-stdstring) which means this code may store all of its data on the stack (for small enough values of `n`) just like the code in your question does! – Brian Rodriguez Aug 26 '17 at 21:10
0

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.

user0042
  • 7,691
  • 3
  • 20
  • 37
amchacon
  • 1,746
  • 14
  • 25