Not sure why the char variables: A, B, and C are exceeding their predefined lengths of 4 digits.
My output is this:
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:
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. ^_^
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. ^_^