C++文件读写以及vector的遍历

写一个文本,然后编写一个程序,打开文本然后将每一个字读取到一个vector对象中。遍历vector,将内容显示到cout。然后利用泛型算法sort(),对文字进行排序。

#include <algorithm>
sort(container.begin(), contaner.end())

再将排序后的结果输出入另一个文件。

#include <iostream>
#include <fstream> //读取文件的头文件
#include <vector> 
#include <algorithm>
using namespace std; 
int main()
{
    ifstream infile("new1.txt"); //验证是否可以打开文件
    if (! infile) //当不能打开时满足条件
    {
        cerr << "please check the file\n"; //cerr和cout一样
    }                                      //但对输出结果无缓存(bufferred)
    ofstream outfile("new2.txt");          //立即显示与终端
    if(! outfile)
    {
        cerr << "please check the file\n";
    }

    string word;                
    vector<string> msg;
    while(infile >> word)    //将文本中的内容读取到字符串word中,知道录取到最后一个字符,返回值为0
    {
        msg.push_back(word); //vector.push_back() 相当于将字符串的内容分配给vector中。类比数组
    }

     unsigned int i;   //为什么是unsigned? 因为i需要与vector.size()作比较,后者为unsigned类型
    cout << "unsorted msg: \n";

    for(i = 0; i < msg.size(); i++) //遍历vector msg
    {
        cout << msg[i] << ' ';
    }
    cout << endl;

    sort(msg.begin(), msg.end( )); //进行sort()操作

    /*outfile << "sorted msg: \n";  //写入outfile

    for(i = 0; i < msg.size(); i++) //遍历sort()后的vector msg,再将其写进outfile
    {
        outfile << msg[i] << ' '; 
    }
    outfile << endl;*/
	
	cout << "sorted msg: \n";  //这里选择直接输出看结果(与写如outfile中的内容相同)

    for(i = 0; i < msg.size(); i++) //遍历sort()后的vector msg
    {
        cout << msg[i] << ' '; 
    }
    cout << endl;
	
    system("pause");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值