C++ Code: Write a program that opens a file of the users choice that contains a
ID: 3801762 • Letter: C
Question
C++ Code:
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
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Sample birthday files:
bday1.txt
-------------------------------------------------------------------------------------------------------------------------------------------
bday2.txt
------------------------------------------------------------------------------------------------------------------
Example 1(user input is Italic):
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 <string>
#include <fstream>
using namespace std;
int getint(string s)
{
int ans=0;
for(int i=0;i<s.length();i++)
{
ans = ans*10 + (s[i]-'0');
}
return ans;
}
int main()
{
string name;
cout<<"Enter a file name:";
cin>>name;
ifstream myfile(name);
int d,m,y;
char c1,c2,c3;
int date[12][31];
int mon[12];
for(int i=0;i<12;i++)
{
for(int j=0;j<31;j++)
{
date[i][j]=0;
}
}
for(int i=0;i<12;i++)
{
mon[i]=0;
}
string s,token;
int pos;
while(getline(myfile,s))
{
//cout<<line<<endl;
pos = s.find("/");
token = s.substr(0, pos);
m = getint(token);
s.erase(0, pos + 1);
pos = s.find("/");
token = s.substr(0, pos);
d = getint(token);
s.erase(0, pos + 1);
pos = s.find("/");
token = s.substr(0, pos);
y = getint(token);
s.erase(0, pos + 1);
//cout<<m<<"/"<<d<<"/"<<y<<endl;
mon[m-1]++;
date[m-1][d-1]++;
}
int mx1=0,mx2=0;
for(int i=0;i<12;i++)
{
for(int j=0;j<31;j++)
{
if(date[i][j]>date[mx1][mx2])
{
mx1=i;
mx2=j;
}
}
}
int mxm=0;
for(int i=0;i<12;i++)
{
if(mon[i]>mon[mxm])
{
mxm=i;
}
}
//cout<<date[0][18]<<' '<<date[7][14]<<endl;
cout<<"Most common birthday:"<<endl;
cout<<mx1+1<<"/"<<mx2+1<<endl;
cout<<"Most common birthday month:"<<endl;
cout<<mxm+1<<endl;
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.