Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initializing char array with spaces

Tags:

c++

c

string

char

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

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] = '\0';

Is there a better way for above?

like image 861
ravi Avatar asked Apr 30 '12 13:04

ravi


People also ask

How do you initialize a char array?

You can initialize a one-dimensional character array by specifying: A brace-enclosed comma-separated list of constants, each of which can be contained in a character. A string constant (braces surrounding the constant are optional)

How do you initialize a char array to null in C++?

You can't initialise a char array with NULL , arrays can never be NULL . You seem to be mixing up pointers and arrays. A pointer could be initialised with NULL . char str[5] = {0};

How do you initialize a char array in Java?

Initializing Char Array A char array can be initialized by conferring to it a default size. char [] JavaCharArray = new char [ 4 ];

How initialization of a character array can be done in C?

Initializing array with a string (Method 1):char arr[] = {'c','o','d','e','\0'}; In the above declaration/initialization, we have initialized array with a series of character followed by a '\0' (null) byte. The null byte is required as a terminating byte when string is read as a whole.


1 Answers

std::string foo(num_space_req,' ');
like image 85
bames53 Avatar answered Sep 18 '22 01:09

bames53