C++ Write a program that opens a file of the users choice that contains a list o
ID: 3802134 • Letter: C
Question
C++
Write a program that opens a file of the users choice that contains a list of birthdays. Extract from this file two things: (1) the date with the most common birthday (all of them) and (2) the month with the most people born. We will not test for a tie in either of these statistics. The file tested will always be in the format: mm/dd/yyyy Example 1 (user input is underlined): Enter file name: bday1.txt Most common birthday: 1/1 Most common birthday month: 3 Example 2 (user input is underlined):
Enter file name: bday2.txt Most common birthday: 8/15 Most common birthday month: 8
Explanation / Answer
#include <iostream>
#include <fstream>
#include <string>
#include<cstring>
#include<vector>
#include<limits.h>
using namespace std;
void MostCommonBirthday(vector<int>& dd,vector<int>& mm)
{
vector<int> count;
for(int i=0;i<dd.size();i++)
count.push_back(0);
for(int i=0;i<dd.size();i++)
{
for(int j=i+1;j<dd.size();j++)
{
if(dd[j]==dd[i] && mm[i]==mm[j])
count[i]=count[i]+1;
}
}
int max=INT_MIN,index;
for(int i=0;i<dd.size();i++)
{
if(count[i]>max)
{
index=i;
max=count[i];
}
}
cout<<"MostCommonBirthday: "<<mm[index]<<"/"<<dd[index]<<endl;
}
int MostCommonMonth(vector<int>& a, int k)
{
for (int i = 0; i< a.size(); i++)
a[a[i]%k] += k;
int max = a[0], result = 0;
for (int i = 1; i < a.size(); i++)
{
if (a[i] > max)
{
max = a[i];
result = i;
}
}
return result;
}
int main () {
string line;
string filename;
cout<<"Enter the filename: ";
cin>>filename;
int month,day,year;
vector<int>dd,mm,yy;
ifstream myfile (filename);
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
cout<<"line="<<line<<endl;
char * cstr = new char [line.length()+1];
strcpy (cstr, line.c_str());
sscanf(cstr," %d/%d/%d ", &month,&day,&year);
dd.push_back(day);
mm.push_back(month);
yy.push_back(year);
}
MostCommonBirthday(dd,mm);
cout<<"MostCommonMonth= "<<MostCommonMonth(mm,13)<<endl; //maximum no of months 12
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.