从一个文本文件中读取内容并打印,之后利用sort函数将内容排序后输出到新的文件中

/* Open a file, copy its content to vector container and print.
   Then sort the contents using 'sort()' and output to another file(date and time included). */
#include
#include        // for class string
#include       // for file I/O
#include        // for container vector
#include     // for mthod sort()
using namespace std;

int main()
{
    vector vec;
    string val;
    ifstream infile("C:\\Users\\Desktop\\1.7.txt");  // pay attention to the description of escape sequence
    if(!infile)

        cerr << "Oops! unable to open the file -- 1.7.txt.\n";

    ofstream outfile("C:\\Users\\Desktop\\1.7.1.txt", ios_base::app);    // path can be different

    // 若不加后缀,则每次都会将原先内容覆盖  

     if(!outfile)        // put at the beginning in case of file open failed

        cout << "Oops! unable to open the file -- 1.7.1.txt.\n";

    while(infile >> val)

        vec.push_back(val);

    cout << "Unsorted string: \n";

    for(int i = 0; i < vec.size(); ++i)
        cout << vec[i] << ' ';
    cout << endl;

    sort(vec.begin(), vec.end());

    outfile << "Sorted string:  (" << __DATE__ << " - " << __TIME__ << ")" << endl;   

    // add the date and time of sorting

        for(int i = 0; i < vec.size(); ++i)
            outfile << vec[i] << ' ';

        outfile << endl;

    return 0;

    }


你可能感兴趣的:(从一个文本文件中读取内容并打印,之后利用sort函数将内容排序后输出到新的文件中)