C++ Code : Problem A: Birthdays again... ( this code most be written in C++, Tha
ID: 3802742 • Letter: C
Question
C++ Code:
Problem A: Birthdays again... (this code most be written in C++, Thanks)
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
c++ code:
#include <bits/stdc++.h>
using namespace std;
int main()
{
cout << "Enter name of input file!" << endl;
string filename;
cin >> filename;
string line;
ifstream myfile (filename.c_str());
std::map<int, int> day;
std::map<int, int> month;
std::map<int,int>::iterator it;
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
string str = line;
for (int i=0; i<str.length(); i++)
{
if (str[i] == '/')
str[i] = ' ';
}
line = str;
string buf; // Have a buffer string
stringstream ss(line); // Insert the string into a stream
vector<string> tokens; // Create vector to hold our words
while (ss >> buf)
tokens.push_back(buf);
it = day.find(atoi(tokens[0].c_str()) );
if (it != day.end())
{
day[atoi(tokens[0].c_str())] += 1;
}
else
{
day[atoi(tokens[0].c_str())] = 1;
}
it = month.find(atoi(tokens[1].c_str()) );
if (it != month.end())
{
month[atoi(tokens[1].c_str())] += 1;
}
else
{
month[atoi(tokens[1].c_str())] = 1;
}
}
int dayfreq = 0;
int bestday = 0;
for (it=day.begin(); it!=day.end(); ++it)
{
if(it->second >= dayfreq)
{
dayfreq = it->second;
bestday = it->first;
}
}
int monthfreq = 0;
int bestmonth = 0;
for (it= month.begin(); it!=month.end(); ++it)
{
if(it->second >= monthfreq)
{
monthfreq = it->second;
bestmonth = it->first;
}
}
cout << "Most frequent birthday is " << bestmonth << endl;
cout << "Most frequent Month is " << bestday << endl;
myfile.close();
}
else
{
cout << "Unable to open file" << endl;
exit(1);
}
return 0;
}
Sample Output:
Enter name of input file!
birth1.txt
Most frequent birthday is 1
Most frequent Month is 3
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.