把文件中的一组整数排序后输出到另一个文件中(c/c++)

来源:互联网 发布:java获取tomcat的端口 编辑:程序博客网 时间:2024/05/19 03:45

我是自己先建立一个文本文件a.txt,里面写了整数:
1 23 45 67 89 0

C语言实现:

#include<stdio.h>#include<errno.h>#include<stdlib.h>void sort(int *a,int len){    int i;    int j;    for(i = 0; i < len-1; i++)    {        for(j = 0; j < len-i-1; j++)    {        if(a[j] > a[j+1])        {            int temp = a[j];        a[j] = a[j+1];        a[j+1] = temp;        }    }    }}int main(){    int i = 0;    int len;    int temp;    int a[100];    FILE *fp;    fp = fopen("a.txt","r");    if(fp == NULL)    {        perror("fopen");    exit(1);    }    while(!feof(fp))    {        fscanf(fp,"%d",&temp);    a[i] = temp;    i++;    }    fclose(fp);    sort(a,i-1);    len = i-1;    fp = fopen("b.txt","w+");    if(fp == NULL)    {        perror("fopen2:");    exit(1);    }    for(i = 0; i < len; i++)    {        fprintf(fp,"%d\n",a[i]);    }    fclose(fp);    return 0;}

b.txt里面的内容:
这里写图片描述

c++版本:

#include<iostream>#include<errno.h>#include<fstream>#include<vector>using namespace std;void sort(vector<int> &data){    int count = data.size();    int i;    int j;    for(i = 0 ; i < count-1; i++)    {        for(j = 0; j < count-i-1; j++)    {        if(data[j] > data[j+1])        {            int temp = data[j];        data[j] = data[j+1];        data[j+1] = temp;        }    }    }}int main(){    int i = 0;    int len;    int temp;    int a[100];    vector<int> data;    ifstream fin("a.txt");    if(!fin)    {        perror("fin:");    exit(1);    }    while(!fin.eof())    {        fin>>temp;    if(fin.fail())    {        break;    }    printf("temp = %d\n",temp);    data.push_back(temp);           cout<<data.size()<<endl;    }    fin.close();    sort(data);    ofstream fout("b.txt");    if(!fout)    {        perror("fopen2:");    exit(1);    }    for(i = 0; i < data.size(); i++)    {        fout<<data[i] <<endl;    }    fout.close();    return 0;}

b.txt的内容如上图所示是一样的

阅读全文
0 0
原创粉丝点击