i have this data structure class and our instructor hasnt tought us anything and she's demanding for a project this midterm. can anyone help me? plss...
here's the problem... create a program that will sort a list of strings entered by the user using arrays..
ex. //user will input number of strings to sort// : 2
//user will input 2 strings// : iloveyou //array[0]
: counterstrike //array[1]
//program will sort the strings alphabetically: counterstrike
: iloveyou
Wow. We went from "I'll check it out" to "it didn't work out" in three minutes.
strcmp(char *,char *) (http://www.cplusplus.com/reference/clibrary/cstring/strcmp.html). In a nutshell:
strcmp(a,b)==0 //The strings are equal
strcmp(a,b)<0 //a (when in ascendant order) appears before b
strcmp(a,b)>0 //a (when in ascendant order) appears after b
#include<iostream.h>
int main()
{
int t,y;
char a[100];
cout<<"input number of names";
cin>>t;
for(y=0;y!=t;y++)
{
cout<<"enter name<one word>"<<endl;
cin>>a;
cout<<a<<endl;
}
return 0;
}
this should how the program would look like.. but after acepting names... it should display the names entered but already in ascending order..
char a[100] is merely a static array of characters (i.e. a string).
To have an array of strings, you need to use something more like char *a[100]. You'll be royally screwed if the user chooses to input more than 100 names.
You aren't initializing the pointers.
My mistake. Since this appears to be homework, let's take a different approach, since I'm not sure if you should be using new, and use char a[100][100].
Now the input should work.
This section has all the sorts you could possibly need. Choose one near the top and implement it. Come back and I'll nitpick your implementation for you. http://en.wikipedia.org/wiki/Sorting_algorithm#Summaries_of_popular_sorting_algorithms
As helios mentioned above you can use strcmp() and compare c-type strings:
strcmp(a,b)==0 //The strings are equal
strcmp(a,b)<0 //a (when in ascendant order) appears before b
strcmp(a,b)>0 //a (when in ascendant order) appears after b
You use any kind of sorting algorithm you want with the difference of instead of comparing numbers you use the strcmp() function to compare c-type strings.