Comparing strings within a string array

Hi, I am trying to compare strings within a string array. I want to compare all the strings and output the one string that comes first alphabetically. So far, I have tried using std::string::compare. However, the program keeps outputting "baseballarmour" when it should just be outputting "armour." Curiously, when I change "baseball" to "gate" the output correctly displays "armour." Not sure what is going on here. Could anyone please help me out with this? I am really confused.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main() {

    string stringArray[4] = {"lion", "baseball", "cage", "armour"};

    for (int i = 0; i < 4; ++i) {
	
        stringArray[i].compare(stringArray[i + 1]);
			
	if (stringArray[i].compare(stringArray[i + 1]) < 0) {

	    cout << stringArray[i];

        }
     }
    
     return 0;
}
I'm not sure if this will work for you, but I would do something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <algorithm>
#include <string>

int main() 
{
	std::string stringArray[] = { "lion", "baseball", "cage", "armour" };

	//get the size of the array
	unsigned size = sizeof(stringArray) / sizeof(stringArray[0]);  

	//sort the array with the "sort" function defined in <algorithm>
	sort(stringArray, stringArray + size);
	
	//print out in alphabetical order
	for (unsigned i = 0; i < size; i++)
	{
		std::cout << stringArray[i] << ' ';
	}

	std::cin.ignore();
	std::cin.get();
	return 0;
}


Or you can just sort the array with your favorite sorting algorithm if you don't want to #include <algorithm>
Last edited on
sasauke,

Thank you for replying. The method you used to sort the array is very nice! However, is there a way that I can print out just the element in the array that occurs first in the alphabet. That is, if I just want to display armour after sorting, how would I do that? I tried
cout << stringArray[0] but that didn't work.
I haven't included using namespace std; in the code above. So you'll have to specify the namespace in which the "cout" command is. So if you do std::cout << stringArray[0] it should work fine.

Sorry for the late reply, I was caught in something XD
Last edited on
sasauke,

Thank you very much for taking the time to help me out. I really do appreciate it.
Topic archived. No new replies allowed.