C++ 用空格初始化字符数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10384632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:00:01  来源:igfitidea点击:

initializing char array with spaces

c++cstringchar

提问by ravi

I want a 20 character NULL('\0') terminating string filled with white spaces.

我想要一个用空格填充的 20 个字符的 NULL('\0') 终止字符串。

Currently I am doing it in following way

目前我正在按照以下方式进行

char foo[20];  
for (i = 0; i < num_space_req; i++)        //num_space_req < 20  
{  
    foo[i] = ' ';  
}

foo[num_space_req] = '
memset(foo, ' ', num_space_req);
foo[num_space_req] = '
std::string foo(num_space_req,' ');
';
';

Is there a better way for above?

以上有更好的方法吗?

回答by Oliver Charlesworth

You can use the following to initialize the array to spaces:

您可以使用以下命令将数组初始化为空格:

std::fill(foo, foo + num_space_req, ' ');
// or
std::fill_n(foo, num_space_req, ' ');

回答by bames53

memset (foo, ' ', num_space_req)

回答by ravi

Since the question has a C++ tag, the idiomatic way would be:

由于问题有一个 C++ 标签,惯用的方法是:

char bla[20];

memset(bla, ' ', sizeof bla - 1);
bla[sizeof bla - 1] = '
char bla[20] = {[0 ... 18] = ' ', [19] = '
memset(foo, ' ', sizeof(foo) -1);
foo[20] = '
memset( foo, ' ', sizeof(foo) -1 );
memset( foo, ' ', 19 );
memset( foo, ' ', 19 * sizeof(char) );
';
'};
';

Note that it doesn't work in C.

请注意,它在 C 中不起作用。

回答by Kh?i

You may use memsetfor that kind of thing.

你可以memset用于那种事情。

#include <cstring>
void makespace(char *foo, size_t size) {
  memset((void*)&foo, ' ', size - 1);
  foo[size] = 0;
}
// ...
makespace(foo, 20);

http://www.cplusplus.com/reference/clibrary/cstring/memset/

http://www.cplusplus.com/reference/clibrary/cstring/memset/

回答by ouah

As @OliCharlesworthsaid, the best way is to use memset:

正如@OliCharlesworth所说,最好的方法是使用memset

##代码##

Note that in GNU C, you can also use the following extension (range designated initializers):

请注意,在 GNU C 中,您还可以使用以下扩展名(范围指定初始值设定项):

##代码##

回答by octopusgrabbus

If you want the array initialized at compile time, you can modify your char foo[20];declaration as follows:

如果你想在编译时初始化数组,你可以修改你的 charfoo[20];声明如下:

char foo[20] = {0x20};

char foo[20] = {0x20};

If you need to initialize the array to spaces at run time, then you can use the following:

如果需要在运行时将数组初始化为空格,则可以使用以下命令:

##代码##

回答by Grimm The Opiner

memset MIGHT be better optimised than your for loop, it might be exactly the same. pick one of:

memset 可能比您的 for 循环更好地优化,它可能完全相同。选择其中之一:

##代码##

回答by perreal

##代码##