Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Strings

Status
Not open for further replies.

redshadow

Programmer
Joined
May 24, 2001
Messages
70
Location
PH
I am just wondering why this code produces different results

#include <stdio.h>
#include <string.h>
char names[5][25],temp[25];
int x;
void main()
{
for (x=0;x<=4;x++)
{
scanf(&quot;%s&quot;,names[x]);
}
for (x = 0;x<=4;x++)
{
printf(&quot;%s&quot;,names[x]);
}
// the above works well
//but this one didn't produces the correct output

for (x=0;x<=4x++)
{
if(strcmp(names[x],names[x+1]))
{
temp = names[x];
names[x] = names[x+1];
names[x+1] = temp;
}
}
for (x=0;x<=5;x++)
{
//here i suppose it would print names
//in ascending order but instead characters became
//garbled.
printf(&quot;%s&quot;,names[x]);
}


a sample result after inputting names: Antonio tony Arman Rex
would produce Antonio nyArm etc. depending on input

can anyone help me correct this code? I want to sort names using strcmp function.

Thanks in advance.

 
Try changing the comparison section of code to either one of these:

--------------------------------------------

// add brackets around each x+1 so it is evaluated first

for (x = 0; x <= 4; x++)
{
if (strcmp(names[x], names[ ( x+1 ) ] ))
{
temp = names[x];
names[x] = names[ ( x+1 ) ];
names[ ( x+1 ) ] = temp;

// unrelated to the garble problem, but
// if we've switched a set of values
// start the sort over again to make sure
// lower sets of values are also compared...
// not the most efficient sort, but oh well.
x = -1;
continue;
}
}

-------- or ----------

// replace each x+1 with the pre-evaluated y value

int y = 0;

for (x = 0; x <= 4; x++)
{
y = x + 1;

if (strcmp(names[x],names[y]))
{
temp = names[x];
names[x] = names[y];
names[y] = temp;

// start the sort over again...
x = -1;
continue;
}
}

--------------------------------------------
 
during the swap, try changing

temp = names[x];
names[x] = names[x+1];
names[x+1] = temp;

to

strcpy(temp,names[x]);
strcpy(names[x],names[x+1]);
strcpy(names[x+1],temp);

if you actually want to swap all the characters of an entry in the character arrays...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top