Chracter array

GiLtY

Golden Member
Sep 10, 2000
1,487
1
0
Hello all i need help on this simple question that I've been trying to figure but failed to find the answer about character array:

Today I was trying to write a program that simulates an answer machine, and I had a model which I copied off from a website, one of the variables is char Messages[25][100];
I wasn't sure what do to because I never worked with a variable with two arrays. But from what my teacher told me, he said that it simply says that there are 25 rows and each row can hold 100 characters maximum(well, technically it should be 99, considering the null terminator). But still I couldn't find a way to store characters in this situation.
For example, how would I input the characters "hello world" into the first row? I tried Messages[1]="hello world" but it didn't work, i tried to add [100] after [1] and it didn't work out also. I just need an example on how to input characters in this situation, thank you for your help in advance :D
 

indd

Senior member
Oct 16, 1999
313
0
0
What you want to use is the strcpy command (in string.h). here's an example (we'll also look at strcat):

#include <string.h>
#include <iostream.h>

void main() {

char firstname[20];
char lastname[20];
char fullname[41]; // leave an extra char for the space

strcpy( firstname, &quot;Billy-bob&quot; ); // changes firstname to &quot;Billy-bob&quot;
strcpy( lastname, &quot;Gates&quot; ); // changes lastname to &quot;Gates&quot;
strcpy( fullname, firstname ); // changes fullname to value in firstname
strcat( fullname, &quot; &quot; ); // adds a space to the end of fullname
strcat( fullname, lastname ); // adds the value in lastname to fullname

cout << fullname << endl;

return;

}

This program should output:
Billy-bob Gates

(Edit) to answer your question though, there's really two ways you can put &quot;hello world&quot; into the first row.

Way #1:
Messages[0][0] = 'h';
Messages[0][1] = 'e';
Messages[0][2] = 'l';
...
Messages[0][8] = 'r';
Messages[0][9] = 'l';
Messages[0][10] = 'd';

But that really sucks

Way #2:
You do the strcpy as illustrated above..
strcpy( Messages[0], &quot;hello world&quot; );


hope this helps,
indd




 

bigshooter

Platinum Member
Oct 12, 1999
2,157
0
71
also remember that the first row and column is actually 0 and the last row is 99. If you tried to use 100 that would be the 101st row or column of your array, and you only have 100.
 

BFG10K

Lifer
Aug 14, 2000
22,709
2,998
126
I tried Messages[1]=&quot;hello world&quot; but it didn't work

No, you need to use strcpy if you're using character arrays.

char messages [25][100];

strcpy (messages [0], &quot;hello world&quot;);
strcpy (messages [1], &quot;bye world&quot;);
....
strcpy (messages [24], &quot;last message&quot;);

Keep in mind that array indices go from 0 to the array size - 1.

There is a much better way to do this by using pointers, but you need to be more experienced to understand it.