I'm using Borland C++ and i need to make program where you enter a string in which the words are seprated by space. After input i need to sort these words into alphabetical order, but something is wrong. Cause when i enter like " x b a" it prints out "a b" but when i enter "abc abb aba" it sorts it ok. Where is the problem? I would be really thankful if anybody could help me. Thank you.
Code:
#include <stdio.h>
#include <string.h>
#include <conio.h>
#include <iostream.h>
#include <stdlib.h>
void main ()
{
clrscr();
char rinda[200];
printf("Enter string [ words are separated with space ]\n");
gets(rinda);
char * pch;
char * pch2[100];
char * temp[100];
int words,j;
j=0;
words=0;
pch = strtok (rinda," ");
while (pch != NULL)
{
pch2[j]=pch;
words=words+1;
j=j+1;
pch = strtok (NULL, " ,.-");
}
cout << "Before sorting:" <<endl;
for (int x=0;x<words;x++)
cout << pch2[x]<<endl;
for (int i=1; i<=words; i++) {
for ( int z=0;z<=i;z++ ) {
if (strcmp(pch2[z],pch2[z+1]) > 0) {
temp[z]=pch2[z];
pch2[z]=pch2[z+1];
pch2[z+1]=temp[z];
}
}
}
cout << "After sorting:" <<endl;
for (int g=0;g<words;g++)
cout << pch2[g]<<endl;
getche();
}