Quick beginner question

Hey everybody, this is my first post here. C/C++ is my first language, and I just started about six months ago. I was playing with character arrays and hit a bump using two separate(not nested) for loops. I was trying to accept keyboard input and store two separate arrays. Somehow my second array always contains the first when called. I have a vague understanding of my problem, but I was hoping that someone might offer a brief explanation.

-Dave



# include <iostream>

using namespace std;

void getArrays(char [], char []);

int main()
{

char array1[3], array2[3];

getArrays(array1, array2);

cout << array1 << endl << array2;

}
void getArrays(char array1[3], char array2[3])
{

int i, j;

for(i = 0; i < 3; i++)
{
cin >> array2[i];
}

for(j = 0; j < 3; j++)
{
cin >> array1[j];
}
}


When I input aaabbb. I was hoping my output would be:
aaa
bbb

Instead it is:
aaa
bbbaaa




[code] "Please use code tags" [/code]
Null-terminated strings
Thank you, I was wondering how to post code correctly. I changed the code to this and it works properly. Much appreciated.

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
# include <iostream>

using namespace std;

void getArrays(char [], char []);

int main()
{

    char array1[4], array2[4];

    getArrays(array1, array2);

    cout << array1 << endl << array2;

}

void getArrays(char array1[4], char array2[4])

{
    int i, j;

    array1[3] = '\0';
    array2[3] = '\0';

    for(i = 0; i < 3; i++)
        {
        cin >> array2[i];
        }

    for(j = 0; j < 3; j++)
        {
        cin >> array1[j];
        }
}
Topic archived. No new replies allowed.