Question

#include <iostream>
#include <string>

using namespace std;

int main()
{
    int n;

    cout << "Enter n: ";
    cin >> n;
    cout << "Enter " << n << "names";

    for(int i=0; i<n; i++)
    {





    system("pause>0");
    return 0;
}

This is my unfinished code. I'm required to enter a number then it will ask me to enter n names. and after entering the names the program should sort the names alphabetically. How will I do that in Looping? I'm very confused in the looping part. Yeah, I know what I will code when I'm finished in looping. I'm just confused and having problems in this part. Thanks in Advance!

Was it helpful?

Solution

Here's an STL version of what you're trying to do:

#include <iostream>
#include <vector>
#include <cstdlib>
#include <string>
#include <algorithm>

int main() {
    std::vector<std::string> names;

    int num = 0;
    std::cout << "Please enter a number: ";
    std::cin >> num;
    std::cout << "\n";

    std::string name;

    for (int i = 0; i < num; ++i) {
        std::cout << "Please enter name(" << (i+1) << "): ";
        std::cin >> name;
        names.push_back(name);
    }

    //sort the vector:
    std::sort(names.begin(), names.end());

    std::cout << "The sorted names are: \n";

    for (int i=0; i<num; ++i) {
        std::cout << names[i] << "\n";
    }

    return 0;
}

However, this version is a case-sensitive sort, so whether or not that performs to your requirements could be problematic. So, a possible next step to get closer to case-insensitive sorting is to use this bit of code before the vector is sorted:

    //transform the vector of strings into lowercase for case-insensitive comparison
    for (std::vector<std::string>::iterator it=names.begin(); it != names.end(); ++it) {
        name = *it;
        std::transform(name.begin(), name.end(), name.begin(), ::tolower);
        *it = name;
    }

The only caveat with this method is that all your string will be converted to lowercase, though.

REFERENCES:

https://stackoverflow.com/a/688068/866930

How to convert std::string to lower case?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top