Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

c++ - How to alphabetically sort strings?

I have been trying to use this c++ program to sort 5 names alphabetically:

#include <iostream>
#include <cstring>
#include <conio.h>
using namespace std;

int main()
{
char names[5][100];
int x,y,z;

char exchange[100];

cout << "Enter five names...
";

for(x=1;x<=5;x++)
{
    cout << x << ". ";
    cin >> names[x-1];
}
getch();

for(x=0;x<=5-2;x++)
{
    for(y=0;y<=5-2;y++)
    {
        for(z=0;z<=99;z++)
        {
            if(int(names[y][z])>int(names[y+1][z]))
            {   
                strcpy(exchange,names[y]);
                strcpy(names[y],names[y+1]);
                strcpy(names[y+1],exchange);
                break;
            }
        }   
    }
}   

for(x=0;x<=5-1;x++)
    cout << names[x];

return 0;
}

If I enter Earl, Don, Chris, Bill, and Andy respectively, I get this:

AndyEarlDonChrisBill

Could someone please tell me whats wrong with my program?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could use std::set or std::multiset (if you will allow repeated items) of strings, and it will keep the items sorted automatically (you could even change the sorting criteria if you want).

#include <iostream>
#include <set>
#include <algorithm>

void print(const std::string& item)
{
    std::cout << item << std::endl;
}

int main()
{
    std::set<std::string> sortedItems;

    for(int i = 1; i <= 5; ++i)
    {
        std::string name;
        std::cout << i << ". ";
        std::cin >> name;

        sortedItems.insert(name);
    }

    std::for_each(sortedItems.begin(), sortedItems.end(), &print);
    return 0;
}

input:

  1. Gerardo
  2. Carlos
  3. Kamilo
  4. Angel
  5. Bosco

output:

Angel
Bosco
Carlos
Gerardo
Kamilo

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...