图形

美丽的世界

第一个程序,文件读写,排序。

// Sort.cpp : main project file.
//my first sort program.

#include "stdafx.h"

#include <algorithm>
#include <vector>

#include <iostream>
#include <fstream>
#include <string>

using namespace System;
using namespace std;    //iostream,algorithm,vector is included in std.

int main(void)
{
   
    //用于存放排序数字的数组。vector 是一个动态数组
    int temp ;
    vector<int> sortvector;
    //从文件中读出数字,放入sortvector中
    fstream fin("sort.txt",ios::in); //用相对路径,文件在\Sort下,即project的同名文件夹下。
   
    if(!fin)
    {
        cout<<"Cannot open file.\n";
        return 1;
    }
/*  我的方案
    while(!fin.eof())//此处,如果用while(fin),循环结束时会将最后个数字读两次,不知道是什么原因。改成这样就可以了。
    {
        fin>>temp;
       
        sortvector.insert(sortvector.end(),temp);
    }
*/
    //大师的方案
    while(fin>>temp)
    {
        sortvector.push_back(temp);    //这样的存储开销会小。
    }
    /*陪充一点读字符串的方法
    string s;
    while(getline(fin,s)) //这样对一行数据的长度没有限制
    {
        fout<<s<<endl;
        cout<<s<<endl;
    }
    */

    fin.close();
   
    //排序
    sort(sortvector.begin(),sortvector.end());

    //输出到屏幕和文件sorted.txt
    vector<int>::iterator it;
    //write the sorted number into the file sorted.txt
    fstream fout("sorted.txt",ios::out);

    cout << "myvector contains:";
    for (it=sortvector.begin(); it!=sortvector.end(); ++it)
    {
        cout << " " << *it;
        fout<<*it<<" ";
    }
    cout << endl;

    fout.close();

    //这个地方pause一下,用来查看显示结果。这样比用cin要好些。
    //或者在此处添加brekpoint也可以。

    system("pause");
   
    return 0;
}
小结:
1.文件的路径要用\\,第一条\是转义。 如果用相对路径,要放到project下的同名文件夹下,好多其它文件都在那个文件夹里,这好像是一点改进。
2.vector实现动态数组还不错。
3.文件读的结束判断。有两种:while(fin>>temp)或者while(!fin.eof())
4.用system("pause");暂停,方便查看结果。

posted on 2007-11-19 15:07  songlotus  阅读(374)  评论(0编辑  收藏  举报

导航