Jun 15, 2013 at 10:57am UTC
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 Jun 15, 2013 at 10:58am UTC
Jun 15, 2013 at 11:01am UTC
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 Jun 15, 2013 at 11:03am UTC
Jun 15, 2013 at 12:07pm UTC
@The illusionist mirage
cire didn't use a library function. He wrote his own function to copy strings.