0

I got a question regarding sorting multiple strings that are entered as such, i need to sort them so that if the list would look like this, i just cant seem to get the strings to be swapped, do i need to be using strcpy? Any help would be great in solving this.


WHAT THE PROGRAM SHOULD LOOK LIKE RUNNING

Please enter the 10 strings to sort.

hedge
tomato
apple
cat
peat moss
potting soil
daisy
rose bush
shovel
grass

The sorted strings are:
apple
cat
daisy
grass
hedge
peat moss
potting soil
rose bush
shovel
tomato
Press any key to continue .

MY CODE

#include <iostream>
#include <cstdlib>

using namespace std;


int main()
{
int i,j,maxLoc,number;
char temp[31];
char myString[10][31];// says i want 10 strings of 30 characters
cout<<"Please enter the 10 strings to sort. "<<endl;
//gets the 10 strings 
 cin.get(myString[0],31);
 cin.ignore();
 cin.get(myString[1],31);
 cin.ignore();
 cin.get(myString[2],31);
 cin.ignore();
 cin.get(myString[3],31);
 cin.ignore();
 cin.get(myString[4],31);
 cin.ignore();
 cin.get(myString[5],31);
 cin.ignore();
 cin.get(myString[6],31);
 cin.ignore();
 cin.get(myString[7],31);
 cin.ignore();
 cin.get(myString[8],31);
 cin.ignore();
 cin.get(myString[9],31);
 
for(i =9; i>0; i--) { // start at the end of the strings
      maxLoc = 0;
      for(j = 0; j <= i; j++) // Find the largest remaining word
          if (strcmp (myString[j],myString[i])<0)
          maxLoc = j;
          
      /* Swap the smallest word with the last unsorted value. */
      temp = myString[i];
      myString[i] = myString[maxLoc];
      myString[maxLoc] = temp;
    } 
system("PAUSE");
 return 0;
}

Edited by Nick Evan: Added code-tags

2
Contributors
1
Reply
2
Views
7 Years
Discussion Span
Last Post by firstPerson
0

*sigh*, Another post without code-tags. If only I had $1000 for every
post without code-tags.

You should be using arrays to get the input first, instead of the ugly hard-coding, and use std::strings like so :

const int MAX_INPUT  = 10;
string userInputs[MAX_INPUT] = { string(""); }
for (pos = 0; pos < MAX_INPUT; ++pos)
 cin >> userInput[pos];

Now make a function called sortUserInputs that takes in an array
of strings, like so :

void sortUserInputs(string *inputs, const int MAX_INPUTS){
 //sorting algo goes here
}

Make those changes, try to sort the user inputs, for example you can
use bubble sort, or selection sort. Then report back if problems occur.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.