Support Forums

Full Version: Something absurdly wrong with char array
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Not sure why the char variables: A, B, and C are exceeding their predefined lengths of 4 digits.

Code:
#include <iostream>
using namespace std;

int main()
{
    char A[4], B[4], C[4];
    char long_char_array[12]={'e','x','a','m','p','l','e','_','t','e','x','t'};

    for(int x=0;x<4;x++)
    {
        A[x] = long_char_array[x];    //supposed to get "exam"
        B[x] = long_char_array[x+4];    //supposed to get "ple_"
        C[x] = long_char_array[x+8];    //supposed to get "text"
    }

    cout<<A<<endl;
    cout<<B<<endl;
    cout<<C<<endl;
}

My output is this:
Code:
examexample_text
ple_examexample_text
textple_examexample_text

As you can see, the first 4 digits of each output is correct, but that excess keeps piling on afterwards! What can I do to keep this from happening?
----------FIXED----------

I'm not in the habit of asking help, but trust me: This had bugged me for over an hour before I asked.

However, I just now figured out my mistake. For those of you with the same mistake, the answer is that with char arrays you need to append your characters with the null string character, or '\0'.

See:
Code:
#include <iostream>
using namespace std;

int main()
{
    char A[5],B[5],C[5];
    char long_char_array[12]={'e','x','a','m','p','l','e','_','t','e','x','t'};

    for(int x=0;x<4;x++)
    {
        A[x] = long_char_array[x];    //supposed to get "exam"
        B[x] = long_char_array[x+4];    //supposed to get "ple_"
        C[x] = long_char_array[x+8];    //supposed to get "text"
    }
    A[4]='\0';
    B[4]='\0';
    C[4]='\0';

    cout<<A<<endl;
    cout<<B<<endl;
    cout<<C<<endl;
}

Notice how I had to make my A,B,C variables 5 digits long instead of 4 at the beginning, then before I "cout'd" them, I assigned their last characters the null digit.

Lesson learned. ^_^
The problem is, your trying to print characters as strings

Code:
cout<<A<<endl;
cout<<B<<endl;
cout<<C<<endl;

Your solution works by changing the characters to C strings...you could have also used

Code:
for (i = 0; i < 4; ++i)
{
std::cout<<A[i];
}
That's true, but my problem was that I needed to treat them as strings eventually; I was taking string variables and feeding them into unsigned int variables using sstringstream.

It worked by appending with the null character, so it's all good now. What I'm doing here is converting hex numbers as a string to unsigned int variables.