排序函数:第二种做法(内有三种子方法)

第二种做法:内有三种子方法;

// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//

#if !defined(AFX_STDAFX_H__E3A2A4D8_18B3_40A0_A613_E0CEA5245DC1__INCLUDED_)
#define AFX_STDAFX_H__E3A2A4D8_18B3_40A0_A613_E0CEA5245DC1__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers

#include <stdio.h>
#include<iostream.h>
#include<fstream.h>
#include<string.h>
#include<iomanip.h>
#include <stdlib.h>

// TODO: reference additional headers your program requires here

//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before

the previous line.

#endif // !defined(AFX_STDAFX_H__E3A2A4D8_18B3_40A0_A613_E0CEA5245DC1__INCLUDE

D_)

**************************************

// stdafx.cpp : source file that includes just the standard includes
// GradeResort2.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information

#include "stdafx.h"

// TODO: reference any additional headers you need in STDAFX.H
// and not in this file

**************************************

#ifndef RECORD_RESORT
#define RECORD_RESORT

#include "stdAfx.h"

#define BUF_SIZE 1024
#define MAX_NUM 200

struct Grade {
char id[12];
char name[20];
int grade;
};

int compare(const void *arg1, const void* arg2);

#endif

***************************************

// GradeResort2.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "GradeResort2.h"
#include <strstrea.h>

int compare(const void *arg1, const void* arg2)
{
Grade *g1, *g2;
g1 = (Grade *) arg1;
g2 = (Grade *) arg2;

if(g1->grade < g2->grade) return -1;
else if(g1->grade == g2->grade) return strcmp(g1->id, g2->id);
else return 1;
}

int main(int argc, char* argv[])
{
Grade gArray[MAX_NUM], tempGrade;
int count = 0;

///*
ifstream fin("oldgrade.txt");
char buf[BUF_SIZE];
while(fin.getline(buf, BUF_SIZE)) {
strstreambuf sbuf = strstreambuf(buf, BUF_SIZE);
istream in(&sbuf);
in >> tempGrade.id >> tempGrade.name >> tempGrade.grade;
gArray[count++] = tempGrade;
}
//*/

/*
ifstream fin("oldgrade.txt");
char buf[BUF_SIZE];
while(fin.getline(buf, BUF_SIZE)) {
sscanf(buf, "%s%s%d", tempGrade.id,
tempGrade.name, &tempGrade.grade);
gArray[count++] = tempGrade;
}
*/

/*
FILE *fin = fopen("oldgrade.txt", "r");
while(fscanf(fin, "%s%s%d", tempGrade.id,
tempGrade.name, &tempGrade.grade) == 3) {
gArray[count++] = tempGrade;
}
*/
qsort(gArray, count, sizeof(Grade), compare);

ofstream fout("sortedGrade.txt");
fout.setf(ios::left);
for(int i=0; i<count; i++) {
tempGrade = gArray[i];
fout << setw(12) << tempGrade.id << " "
<< setw(20) << tempGrade.name << " "
<< setw(4) << tempGrade.grade << endl;
}

return 0;
}

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注