Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Create a C++ program to read in a le of dates, sort the dates, and write them ou

ID: 3538257 • Letter: C

Question

Create a C++ program to read in a le of dates, sort the dates, and write them out to a new file. Each line in the input file will contain three integers in month, day, year order separated by whitespace. A sample file is on the class web site. You must create a DATE struct and then declare an array of DATEs. The arrays size is 500. Your program should read the dates and store them in the array. Next, sort the array in calendar order with a function. Finally, write the sorted array out to a file.


Explanation / Answer

#include<iostream>

#include<string>

#include<fstream>


using namespace std;

struct date{

int day;

int month;

int year;

};


void sort(date* dates,int length){

for(int i =0;i < length;i++){

date min = dates[i];

int index = i;

for(int j = i+1;j < length;j++){

if(min.year > dates[j].year){

min = dates[j];

index = j;

}

else if(min.year == dates[j].year){

if(min.month > dates[j].month){

min = dates[j];

index = j;

}

else if(min.month == dates[j].month){

if(min.day > dates[j].day){

min = dates[j];

index = j;

}

}

}

}

dates[index] = dates[i];

dates[i] = min;

}

}



int main(){

ifstream input;

input.open ("dates.txt");

date dates[500];

int i =0;

while(!input.eof()){

input >> dates[i].month;

input >> dates[i].day;

input >> dates[i].year;

i++;

}

input.close();

sort(dates,i);

ofstream output;

output.open("sorted.txt");

for(int j = 0;j < i;j++){

output << dates[j].month <<" "<<dates[j].day<<" "<<dates[j].year<<endl;

}

output.close();

}