#include <iostream>
using namespace std;
#include <string>
using std::string;
using std::getline;
int main ()
     char string1[256];
        char string2[256] ;     
        cout << "\nPlease enter the first array string: \n"<<endl;
  gets (string1);
        cout << "\nPlease enter the second array string: \n"<<endl;
  gets (string2);
  int length1 = strlen( string1 );
     int length2 = strlen( string2 );

  if ( ( strlen( string1 )) > ( strlen( string2 )) )
   for ( int i = 0; i < length2; i++ )
    cout<<" "<< *(string1 + i)<< " " << *( string2 +i);
  if ( ( strlen( string1 )) < ( strlen( string2 )) )
   for ( int j = 0; j < length2; j++ )
    cout<<" "<< *(string1 + j) << " " << *( string2 +j);
        if ( ( strlen( string1 )) == ( strlen( string2 )) )
   for ( int k = 0; k < length2; k++ )
    cout<<" "<< *(string1 + k) << " " << *( string2 +k);
    return 0;

basically what i want as output is

for example if string1 is : hello

and string2 is : bye

the output should be : h b e y l e l o

this program basically does what i want it to do

but the thing is that say the string1 is longer than string 2

fir the same example

it prints something like this

: h b e y l e l & o &

where & is a garbage value

how can i get rid of those garbage values

I see some bad programming habits.
(one thing that this tip doesn't mention: if you're using C++, you should be using getline().)

A clearer idea of what the program is trying to do would also be helpful. I'm only guessing, but it sort of looks like you're trying to merge strings with spaces in between. So what are you trying to do when a string is shorter than the other? Of course you're going to get junk filled in. What did you expect?

You might also want to use string instead of c-strings, as you're using C++.

First of all: I agree with Joe, you should use C++ strings. But if you want to use char[], I would rewrite the program like this:


int length1= strlen(string1) - 1, length2=strlen(string2) - 1;
int i1 = 0, i2 =0;
Loop while counter <= length1+length2
    if (i1 <= length1)
           cout << string1[i1];
     if (i2 <= length2)
            cout << string2[i2] ;
     else break;

First I get the number of characters in the string with strlen(). The '-1' is there to discard the '\0' character.
Next I loop print all the characters (length1+length2 = characters to display)
In the loop I check if I've reached the end of the char[]. If that's not the case I print the char and raise the indexnumber for the array.
So I have 2 indexnumbers (i1 and i2) which I check with the length of the array. This way you shouldn't get out of bounds and the program wouldn't output random values anymore.
Note: I didn't check to see if this works..That's up to you

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.