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.
#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>
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 usingnamespace 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