Sort strings from file in C++

2013-11-19
#c++ #howto #snippet

The very simple and common test program is to read bunch of strings from input file (let it be input.txt), sort them and write down to another file (output.txt). There is an implementation with small bug: it adds extra empty line. I’ve modified original code a bit, so now it works correctly (note: if have last empty line in the input, you will have an empty line in the output). Fixed code is provided below.

sortstrings.cpp:

#include <fstream>
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <iterator>

int main(int argc, char **argv)
{
    std::ifstream fin("input.txt");
    std::vector<std::string> array;

    while (true) {
        std::string s;
        getline(fin, s);
        if (fin.eof()) {
            break;
        }
        array.push_back(s);
        std::cout << s << std::endl;
    }
    fin.close();

    std::sort(array.begin(), array.end());

    std::ofstream fout("output.txt");
    std::copy(array.begin(), array.end(), std::ostream_iterator<std::string>(fout, "\n"));
    fout.close();

    return 0;
}