Hello everyone,
I was having this problem of sorting words of a string entered by user where the user enters many strings and words of each string are sorted separately. This had to be done using pointers . Heres my attempt.I dont know where I am going wrong as garbage is being stored in some of the char pointers.
Please help.
Thanks,
comwizz
//Program to read a set of lines and sort each word in the line
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
int i=0,j=0;
char *temp,*p;
int w_len,l_no,q;
cout<<"Enter the number of lines you want to enter ";
cin>>l_no;
char ***a;
a=new char**[l_no];
for(j=0;j<l_no;i++)
{
cout<<"Enter the number of words in the line"<<i+1<<":"<<endl;
cin>>w_len;
*(a+j)=new char*[w_len];
cout<<"Enter the line"<<endl;
cin.getline(p,150,-1);
char *y;
p++;
y++;
for(i=0;i<w_len;i++)
{
int count=0;
y=p;
while((*p!=' ')&&(*p!='.')&&(*p!='\0'))
{
count++;p++;
}
p++;
*(*(a+j)+i)=new char[count];
strncpy(*(*(a+j)+i),y,count);
}
for(i=0;i<w_len;i++)
{
for(int k=0;k<w_len-i-1;j++)
{
if((strcmp(*(*(a+j)+i),*(*(a+j)+i+1)))>0)
{
temp=*(*(a+j)+i);
*(*(a+j)+i)=*(*(a+j)+i+1);
*(*(a+j)+i+1)=temp;
}
}
}
}
for(j=0;j<l_no;j++)
{
cout<<"The correct order for the line"<<j+1<<"is"<<endl;
for(i=0;i<w_len;i++)
{
cout<<*(*(a+j)+i)<<endl;
}
}
}