C++ - 创建具有相同字符的特定大小的空终止 c 样式字符串的更好方法
C++ - A better way to create a null terminated c-style string of specific size with same character
我想创建一个以空字符结尾的 c-style string
,其中每个字符都是 -
(连字符)。我正在使用以下代码块:
char output_str[n + 1];
std::fill(output_str, output_str + n, '-');
output_str[n + 1] = '[=10=]';
1) 是否有更聪明的 C++ 方法 来做到这一点?
2) 当我打印字符串的大小时,输出是 n
,而不是 n + 1
。我是做错了什么还是空字符从未被计算在内?
编辑:
请考虑此代码块而不是上面的代码块:
char output_str[n + 1];
std::fill(output_str, output_str + n, '-');
output_str[n] = '[=11=]';
请忽略关于尺码的问题。
Is there a smarter C++ way to do this?
当然,使用 std::string
来做到这一点:
std::string s(n,'-');
const char* cstyle = s.c_str();
1) Is there a smarter C++ way to do this?
使用字符串 class:
std::string output_str(n,'-');
如果您需要旧 C 风格的字符串
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?
在您的代码中,没有添加第 N 个字符。如果数组预先填充了零,strlen 函数将 return N.
我想创建一个以空字符结尾的 c-style string
,其中每个字符都是 -
(连字符)。我正在使用以下代码块:
char output_str[n + 1];
std::fill(output_str, output_str + n, '-');
output_str[n + 1] = '[=10=]';
1) 是否有更聪明的 C++ 方法 来做到这一点?
2) 当我打印字符串的大小时,输出是 n
,而不是 n + 1
。我是做错了什么还是空字符从未被计算在内?
编辑:
请考虑此代码块而不是上面的代码块:
char output_str[n + 1];
std::fill(output_str, output_str + n, '-');
output_str[n] = '[=11=]';
请忽略关于尺码的问题。
Is there a smarter C++ way to do this?
当然,使用 std::string
来做到这一点:
std::string s(n,'-');
const char* cstyle = s.c_str();
1) Is there a smarter C++ way to do this?
使用字符串 class:
std::string output_str(n,'-');
如果您需要旧 C 风格的字符串
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?
在您的代码中,没有添加第 N 个字符。如果数组预先填充了零,strlen 函数将 return N.