hi,
im trying to receive a string from user, then divide it into groups of strings with 3 elements only.
meaning if input is:
12345 it should give 123 and 45
123456 it should give 123 and 456
1234567 it should give 123 and 456 and 7
anyway what happens based on my code is that it works fine with first two (when it has groups of 3 elements and 2 element, and also when it has groups of all 3 elements) but for the last case (when makes groups of 3 elements and 1 group of 1 element) it shouws as "123 456 7 D"!! meaning it adds one extra character to the last element out of no where!
can anyone tell me what is the problem with my code??
here is my code:
Code:
#include <iostream>
#include <conio>
struct array
{
char first;
char second;
char third;
};
int main ()
{
while(1){
const int SIZE=256;
int size=0;
bool done=0;
char num[SIZE],arr[3];
int i=0,j=1,k=2;
int z=0,x=0;
array *arrPtr;
cin>>num;
for (int i=0;!done && i<SIZE;i++)
if (num[i]!='\0')
size++;
else done=1;
z=size/3;
cout<<"Size is: "<<size<<endl;
if(size%3==0)
{
arrPtr=new array[z];
for(int x=0;x<z;i=i+3,j=j+3,k=k+3,x++)
{
arrPtr[x].first=num[i];
arrPtr[x].second=num[j];
arrPtr[x].third=num[k];
}
for(int x=0;x<z;i=i+3,j=j+3,k=k+3,x++)
{
cout<<arrPtr[x].first<<arrPtr[x].second;
cout<<arrPtr[x].third<<endl;
}
}
else
{
z++;
arrPtr=new array[z];
for(int x=0;x<z;i=i+3,j=j+3,k=k+3,x++)
{
arrPtr[x].first=num[i];
arrPtr[x].second=num[j];
arrPtr[x].third=num[k];
}
x--;
if((size%3)==1)
{
arrPtr[x].second=' ';
arrPtr[x].third=' ';
for(x=0;x<z;x++)
{
cout<<arrPtr[x].first<<arrPtr[x].second;
cout<<arrPtr[x].third<<endl;
}
}
else
{
arrPtr[x].third=' ';
for(x=0;x<z;x++)
{
cout<<arrPtr[x].first<<arrPtr[x].second;
cout<<arrPtr[x].third<<endl;
}
}
}
}
getch();
return 0;
}