Doubt regarding initializing a string

Hello!

I want to declare a character array and then assign it a value. So how to do it without using library functions or loops?

Example:

If I declared this array:
 
char str[20];

how to I assign it this value?
 
"Hello World!"


Thanks
Easiest is to initialize the array on the same line you define it.
char str[20] = "Hello World!";

Otherwise you will have to assign each and every character individually.
1
2
3
4
5
6
7
8
9
10
11
12
13
str[0] = 'H';
str[1] = 'e';
str[2] = 'l';
str[3] = 'l';
str[4] = 'o';
str[5] = ' ';
str[6] = 'W';
str[7] = 'o';
str[8] = 'r';
str[9] = 'l';
str[10] = 'd';
str[11] = '!';
str[12] = '\0'; // this marks the end of the string 
Last edited on
I would like to append that all elements of the array will be initialized.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
str[0] = 'H';
str[1] = 'e';
str[2] = 'l';
str[3] = 'l';
str[4] = 'o';
str[5] = ' ';
str[6] = 'W';
str[7] = 'o';
str[8] = 'r';
str[9] = 'l';
str[10] = 'd';
str[11] = '!';
str[12] = '\0'; // this marks the end of the string 
str[13] = '\0';
str[14] = '\0';
str[15] = '\0';
str[16] = '\0';
str[17] = '\0';
str[18] = '\0';
str[19] = '\0';
@Peter87


I already know both the methods you just mentioned. But I was asking it because I wanted to make a constructor in a class which would assign a default value to its char array members.

Here's my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <cstdio>
#include <cstdlib>

using namespace std;

class person{
                char fname[20];
                char lname[20];
            public:
                void getFname();
                void getLname();
                person();
                person( char [] );
            };

void person::getFname()
{
    cout << "\nEnter first name: ";
    cin.get();
    gets(fname);
}

void person::getLname()
{
    cout << "\nEnter last name: ";
    cin.get();
    gets(lname);
}

person::person()
{
    fname = "First Name";  // here's the problem
}

int main()
{
    system( "cls" );
    return 0;
}


Thanks!
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

void my_strcpy(char* dst, const char*src)
{
    if (!(*dst = *src))
        return ;
    my_strcpy(dst+1, src+1) ;
}

int main()
{
    char str[20] ;
    my_strcpy(str, "Hello world!\n") ;

    std::cout << str ;
}
@cire


If you had read my question, I wanted to to initialize without using library functions, and I know strcpy could have done the job.

Thanks nevertheless
@The illusionist mirage
cire didn't use a library function. He wrote his own function to copy strings.
Topic archived. No new replies allowed.