Hey guys,

I've got one more thing to ask about. How would I go about sorting by "words" rather than characters. In my program, I "read" strings, not characters and yet if I try to "sort" by words, it ends up just sorting the letters in that word.

So "Benny Sun Honey" becomes "eBnny uSn oHney". As you can see, that's wrong.

I'd prefer not to show the code simply because I don't want someone to do it for me (thanks thought), I just want to see what the reasoning could be. If you guys think you need the code, let me know.

However, I'll show my "reasoning" to the code:

for(int i = 0; i < MAX; i++)
{
      if(x[i] > x[i+1])
     {
      swap(x[i], x[i+1])
      }
}

I am really unclear about what you are trying to accomplish...

If you want to sort strings alphabetically, I can help you with some simple code.

If you want to campare two strings, you could use the string class overloaded == equality test.

If you are trying to compare two elements (letters) of a string, you could also use the == equality test.

I am really unclear about what you are trying to accomplish...

If you want to sort strings alphabetically, I can help you with some simple code.

If you want to campare two strings, you could use the string class overloaded == equality test.

If you are trying to compare two elements (letters) of a string, you could also use the == equality test.

I'm trying to sort "words" alphabetically. So, yes, I'm attempting to sort strings alphabetically. However, my attempt has resulted in me sorting "letters" alphabetically.

Sorry for the delay. My monitor is acting up and during the middle of this post, it went blank for about 3 seconds.

EDIT: I mentioned what was occuring in regards to my attempt at alphabetizing.

So "Benny Sun Honey" becomes "eBnny uSn oHney". As you can see, that's wrong.

It should read:

Benny Honey Sun

Instead of letters being swapped in alphabetical order, strings need to be swapped to appear in alphabetical order.

Edited 7 Years Ago by godsgift2dagame: n/a

I'm trying to sort "words" alphabetically. So, yes, I'm attempting to sort strings alphabetically. However, my attempt has resulted in me sorting "letters" alphabetically.

Sorry for the delay. My monitor is acting up and during the middle of this post, it went blank for about 3 seconds.

EDIT: I mentioned what was occuring in regards to my attempt at alphabetizing.

So "Benny Sun Honey" becomes "eBnny uSn oHney". As you can see, that's wrong.

It should read:

Benny Honey Sun

Instead of letters being swapped in alphabetical order, strings need to be swapped to appear in alphabetical order.

First break sentence into words and then you can use some sorting algorithm - e.g. bubble sort to keep it simple.

Z.

Based on limited information and very little code, I will make some assumptions and hopefully offer a solution that makes some sort of sense.

First, I will assume that all 3 words you wish to alphabetize are part of the same string (named 'x'). I will also assume you have 1 white space seperating the words in your string.

If all this is true, I would recommend parsing the string up into 3 individual substrings (words), perform comparisons among these strings in order to determine alphabetical order; and if desired, return all the substrings back into the original string:

#include<string>
#include<algorithm>
#include<cctype>

string x = "Benny Sun Honey";
string words[3];
int prev=-1, curr=-1;

while(curr_pos != string::npos)
{
     prev_pos = curr_pos;
     curr_pos = find(' ', prev_pos+1);
     
     if(curr_pos != string::npos)
          
          words[i] = x.substr(prev_pos+1, (curr_pos - prev_pos));
   
}

Now that you have your three individual words (words[3]), you can test them individually:

for(int i=0; i<2; i++)
{
     for(int j=0; j<words[j].size() && j<words[j+1].size(); j++)
     {        
          if(toupper(words[i][j]) < toupper(wordsl[i+1][j]))
          {
               break;
          }

          else if(toupper(words[i][j]) > toupper(wordsl[i+1][j]))
          {
               swap(words[i], words[i+1]);
               break;
           }
     } 
}

Now if you want, you can return all 3 words (words[3]) back into your original x <string>:

for(int i=0; i<3; i++)
{
     x += words[i] + ' ';
}

Let me know if this is anywhere in the ballpark of what you needed to do.

This code is untested and may contain easy to fix errors. Also, if anyone knows of a better way to do this, please let me know.

Edited 7 Years Ago by Clinton Portis: because.

Error - Line #5 of my alphabetizing algorithm, should be:

for(int j=0; j<words[[B]i[/B]].size() && j<words[[B]i[/B]+1].size(); j++)

Edited 7 Years Ago by Clinton Portis: n/a

Hey guys,

I continued to mess with the code until around 3 AM (it's about 9:30 now). I've gotten much close now, but I'm still stuck in one regard. In my if statement, I'm unable to have the i++ work. What I mean is, the loop doesn't seem to work properly (for me), and I'm kind of "stuck" at the moment.

The original file being read says:

Kentwood
Athena
locker
Nancy
biology
10 speeds
fireworks

and the file that I'm outputting, after some successful swapping reads as the following:

Athena
Kentwood
Nancy
biology
locker
fireworks
fireworks

It should be worth noting some "strings" get lost or thrown away (10 speeds) and some are doubled (fireworks). Interesting...

Here's the code, as of now:

#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;

int main()
{
 	//defining variables
 	const int MAX = 50;
 	string str[MAX];
 	char letter;
 	int count = 20;
 	
 	//giving file names
 	ifstream original;
 	ofstream updated;
 	
 	//opening input file
 	original.open("susan.dat");
	if(original.fail())
	{
   		   cout << "Input file was inaccessible.";
   		   
        }
    
	//opening output file
	updated.open("MGalex.txt");
	if(updated.fail())
	{
   		   cout << "Output file was inaccessible.";
   		   exit(1);
        }
    
        for(int i = 0; i < MAX; i++)
       {
			while(!original.eof())
		        {
			  					original >> str[i];
								
								if(str[i]>str[i+1])
								swap(str[i],str[i+1]);
						  		cout << str[i] << "\n";
		 	}
	}
 	
 	original.close();
 	updated.close();
 	
 	getchar();
	getchar();
	return 0;
}

Edited 7 Years Ago by godsgift2dagame: n/a

The above code you have for original >> extracting words from your text file will only work 'word at a time', until it hits a white space.

Therefore, a word like "10 Speeds" will be put into two separate str[] objects.

One way to get around this, is to use the getline() function. This would work good for your file anyway, because individual words are contained on their own line.

//instead of
original >> str[i];

//try this:
getline(original, str[i]);

You mentioned that, "some words get doubled." It may be because you are testing for eof() in your loop, which would necessitate an extra loop interation before the eof() flag is set to TRUE. Instead, just test the return value of getline(), which will return TRUE if the extraction was successful, else will return FALSE if extraction unsucessful (which would occur at end of file):

//insted of this
while(!original.eof())

//try this:
while(getline(original, str[i]))

Also here, I notice you are trying to use the < operator on two string objects. While this is fine whilst performing boolean logic among individual characters of the string, I do not see anywhere in the <string> class documentation where the < is overloaded to make comparisons between strings. However, I will make a suggestion to help get you pointed in the right direction:

//str[i] resovles to a single string
if(str[i]>str[i+1])

//need to go one step futher to get to individual characters of the string
if(str[i][j]>str[i+1][j])

Since we are at the individual 'char' level of the string, we can perform all boolean logic. This is probably where you need to be in order to determine alphabetization. There may be instances where the first several letters of two different words may be the same. Example: alchohol and alchoholic. (yes, I can stop anytime I want to..)

Edited 7 Years Ago by Clinton Portis: n/a

This article has been dead for over six months. Start a new discussion instead.