/* sort.cpp - Matt Mahoney, mmahoney@cs.fit.edu This program sorts lines of text in lexicographical (ASCII code) order to standard output from the file name given on the command line, or from standard input if no file name is specified, for instance: sort input.txt >output.txt or sort output.txt In lexicographcial order, the lines of text are printed such that the ASCII codes of the first nonmatching characters of consecutive lines are in ascending order. If one line is a prefix of the other, then the shorter line is printed first. In ASCII order, spaces precede digits (0-9), which precede uppercase letters (A-Z), which precede lowercase (a-z). For instance: input.txt (lines may be in any order) 9 10 cat and dog. cat cats. cat Cat car output.txt (sorted) cat 10 9 Cat car cat cat and dog. cats. If a file name argument is supplied and the file does not exist, sort prints an error message to standard error output (not redirected). */ #include #include #include #include #include using namespace std; // sort_and_print(in) reads lines of text from ifstream in (which must // be open, sorts them, and prints the sorted text to standard output. void sort_and_print(istream& in) { vector v; string s; while (getline(in, s)) v.push_back(s); sort(v.begin(), v.end()); for (vector::const_iterator p=v.begin(); p!=v.end(); ++p) cout << *p << "\n"; } // Open argv[1] for reading, or use cin if missing, then sort it. int main(int argc, char** argv) { if (argc>1) { ifstream in(argv[1]); if (in) sort_and_print(in); else cerr << "File " << argv[1] << " not found\n"; } else sort_and_print(cin); return 0; }