D
D
DDD2019-02-23 11:47:51
C++ / C#
DDD, 2019-02-23 11:47:51

How to sort file names alphabetically?

It is necessary to create a file for 5000 names, sort the file of names in alphabetical order and push the sorted data into another file.
Here's what I could do, but for some reason sort doesn't want to sort.

#include <iostream>
#include <fstream>
#include <vector>
#include <random>
#include <cstdlib>
#include <algorithm>

void GenerFile()
{
    std::mt19937 gen{ std::random_device()() };
    std::uniform_int_distribution<int>uid(0, 8);
    std::ofstream f("name.txt");
    if (!f.is_open())
    {
        std::cout << "error file";
    }
    else
    {
        std::vector<std::string>vc = { "Oleg","Galya","Timon","Pumba","Dima","Nataha","Roman","Lera","Grisha" };
        for (int i = 0; i < 5000; ++i)
        {
            f << vc[uid(gen)].c_str() << " ";

        }
        f.close();
    }
}

void Sort(std::vector<std::string>&vct)
{
    std::sort(vct.begin(), vct.end());
    std::ofstream g("sortname.txt");
    for (int i = 0; i < 5000; ++i)
    {
        g << vct[i].c_str() << " ";
    }
    g.close();
}

void ReadFile()
{
    std::ifstream l;
    l.open("name.txt");
    std::vector<std::string>vct(5000);
    for (int i = 0; i < 5000; ++i)
    {
        l >> const_cast<char*>(vct[i].c_str());
    }
    l.close();
    Sort(vct);
}

int main()
{
    GenerFile();
    ReadFile();

    return 0;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2019-02-23
@Kiberchief

l >> const_cast<char*>(vct[i].c_str());

And what, the suspicion did not even crept in that something was wrong here?
Do not do that. Do this l >> vct[i];and you will be happy.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question