Cannot understand 'char' array text problem.
Hi
First off, nice to be here. A really good place for starters and advance users alike. I have begun to refresh my C++ skills after 6 years of electronics study at college. Here is the problem:
This program takes a text in the char array "test" and stores alternate characters in two different char arrays a and b (even and odd positions). (this may not be clear, im really tired) but the code explains in detail.
I am having trouble in getting the output after the 'for' loop. The 'for' loop that supposedly does the main work and also displays the content of two arrays.
The next time I try to display the arrays, its a different output.
Code:
#include <iostream>
#include <string>
using namespace std;
//Initializing two empty (?) char arrays to store the alternate chars from
//the test string.
char a[]="";
char b[]="";
int main()
{
// Initialization of the test srting. using no space to make it simple for now,
// but spaces also work
char test[]="HelloWorldHowAreYou";
cout << "The string is " << test << " of size " << sizeof(test) << endl;
// Loop test to output the string "test" using loop.
// Used unsigned int to avoid any warnings in comparisson.
cout << "\nLoop Test: \n";
for (unsigned int j=0;j<sizeof(test);j++)
{
cout << test[j] << " ";
}
cout << "\n\n\n";
// The main program to store alternate chars in two different char arrays.
// Loop using unsigned int. The output of this process is correct!
for (unsigned int i=0;i<sizeof(test);i++)
{
a[i]=test[(2*i)];
b[i]=test[(2*i)+1];
cout << "a " << i << " is: " << a[i] << endl;
cout << "b " << i << " is: " << b[i] << endl;
}
cout << "\n\n\n";
// This is where it gets really annoying, I dont get a meaningful output.
// Even if the previous 'for' loop correctly places the chars alternatively
// The output given here is completely incorrect. Example: a[3] is supposed to be
// "o" and b[3] = "r", but the output is mixed up.
// I do realize it could be because of the way arrays work, but please
// explain. I would like to understand this better.
cout << "The output after the storing of alternate chars in a,b. \n\n";
for (unsigned int k=0;k<sizeof(test);k++)
{
cout << "a " << k << " is: " << a[k] << endl;
cout << "b " << k << " is: " << b[k] << endl;
}
//cout << "\n" << a << b << endl;
return 0;
}