Oct 28, 2012 at 1:53pm Oct 28, 2012 at 1:53pm UTC
@fstigre.
because you are using character array , right?
so when you display them out , you have to use a looping to print each array of it
Example:
1 2 3 4 5 6
char name[5] = "Jeff" ;
//use looping
for (int i - 0 ; i < 5 ; i ++ ){
cout << name[i] ;//Looping 5 times to print out [0],[1],[2],[3],[4]
}
Last edited on Oct 28, 2012 at 1:53pm Oct 28, 2012 at 1:53pm UTC
Oct 28, 2012 at 2:59pm Oct 28, 2012 at 2:59pm UTC
char name[50] = "Jeff" ;
works as it translates to "initialize an array of 50 chars with jeff"
name = "Jeff" ;
doesnt work as you are trying assign 5 chars to an array of 50
GCC will say "error: incompatible types in assignment of ‘const char [5]’ to ‘char [50]’"
clang will say "error: array type 'char [50]' is not assignable"
Oct 28, 2012 at 3:03pm Oct 28, 2012 at 3:03pm UTC
This works, because the compiler is setting the initial value for the char array:
char name[50] = "Jeff" ;
But this doesn't work, the second line doesn't even compile.
1 2
char name[50];
name = "Jeff" ;
The solution is to use the strcpy() function.
1 2
char name[50];
strcpy(name,"Jeff" );
If you are going to use c-strings like this, it's worth becoming familiar with the related functions, such as strcat, strlen etc.
http://www.cplusplus.com/reference/clibrary/cstring/
Alternatively, just use the C++ string instead:
1 2
string name1;
name1 = "Geoff" ;
Last edited on Oct 28, 2012 at 3:06pm Oct 28, 2012 at 3:06pm UTC
Oct 29, 2012 at 12:55am Oct 29, 2012 at 12:55am UTC
Thank you all very much for the good advice, it now makes more sense.