Sort strings from file in C++

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

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

sortstrings.cpp:

 1#include <fstream>
 2#include <vector>
 3#include <string>
 4#include <iostream>
 5#include <algorithm>
 6#include <iterator>
 7
 8int main(int argc, char **argv)
 9{
10    std::ifstream fin("input.txt");
11    std::vector<std::string> array;
12
13    while (true) {
14        std::string s;
15        getline(fin, s);
16        if (fin.eof()) {
17            break;
18        }
19        array.push_back(s);
20        std::cout << s << std::endl;
21    }
22    fin.close();
23
24    std::sort(array.begin(), array.end());
25
26    std::ofstream fout("output.txt");
27    std::copy(array.begin(), array.end(), std::ostream_iterator<std::string>(fout, "\n"));
28    fout.close();
29
30    return 0;
31}