-
sorting and searching
i wana search an array, then sort it, and then want output to display where in the array that element was found. this is what i've come up with so far, but something's wrong. can anyone point me in the right direction? i'm not getting any syntax errors, so it's gota be the logic itself.
Code:
#include <stdio.h>
#include <conio.h>
#include <string.h>
main()
{
char name[6][10] =
{"Annabelle", "BoDidly", "Joseph", "Leona", "Molly", "Osie"};
int count = 0,
i, j;
char str_temp;
for(i = 0; i <= 5; i = i + 1)
printf("%s\n", name[i]);
printf("Enter the Name you are Searching for: ", name[i]);
scanf("%s", &name[i]);
if("%s" = &name[i])
printf("The Name you Entered was Found. It was in position %d of the array.", &name[i]);
else
printf("Sorry, but the name you entered was not Found.");
getch();
}
Any replies to this thread greatly appreciated. Thanks
-
There are a fair few errors in this from what i can see. You are mainly using the one variable name - that being name[i]
Code:
printf("Enter the Name you are Searching for: ", name[i]);
scanf("%s", &name[i]);
if("%s" = &name[i])
If I can understand what you are trying to do you can't really say if(name[i] == name[i]) because it will always be true, so what i suggest is that as a start you change
Code:
printf("Enter the Name you are Searching for: ", name[i]);
scanf("%s", &name[i]);
to
Code:
printf("Enter the Name you are Searching for:\n");
scanf("%s", searchkey);
You might need to use strcmp() to compare the strings.
Good Luck
-
Here's another error :
>> scanf("%s", &name[i]);
Drop the ampersand '&', should be scanf("%s", name[i]);
>> char str_temp;
Should be char str_temp[SOME_VALUE];, which causes the above statement to change to scanf("%s", str_temp);
Also, you'll have to test each string with the user's input, like this :
Code:
int found = 0;
for( i = 0; i < 6; i++ )
{
if( strcmp( name[i], str_temp ) == 0 )
{
printf( "The Name you Entered was Found. It was in position %d of the array.", i + 1 );
return getch();
}
}
printf("Sorry, but the name you entered was not Found.");
return getch();