I am working on a C++ program. In the main()
function, it will ask the user to input the first and last names of their friends, and the hobbies they have. For example, the user input will be like this:
Erik,French,soccer,END
Jenna,Obrien,soccer,games,END
Ricardo,Waters,games,baseball,END
Which will then output the list of users and the top 5 interests ranked by the number of users who have those interests.
When I run my program and I put in my inputs, the program prints out no output.
Instead of this output:
I tried to use the if
statement break
, but it still shows the same result.
if (hobby != "done"){
users.push_back(user);
}else break;
Is there any way to fix this issue?
main
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include "User.h"
using namespace std;
int main()
{
vector<User> users;
vector<string> allHobbies;
string firstname, lastname, hobby, done;
while (cin >> firstname >> lastname) {
string friendsname = firstname + " " + lastname;
User user(friendsname);
while (cin >> hobby && hobby != "END") {
user.AddHobby(hobby);
allHobbies.push_back(hobby);
}
if (hobby != "done"){
users.push_back(user);
}else break;
}
// Print users
cout << "The Users" << endl;
cout << "=========================" << endl;
for (const auto& user : users) {
cout << user.GetName() << endl;
}
// Count hobby occurrences
sort(allHobbies.begin(), allHobbies.end());
auto last = unique(allHobbies.begin(), allHobbies.end());
vector<pair<string, int>> hobbyCounts;
for (auto it = allHobbies.begin(); it != last; ++it) {
hobbyCounts.push_back(make_pair(*it, count(allHobbies.begin(), allHobbies.end(), *it)));
}
// Sort by count and print top 5
sort(hobbyCounts.begin(), hobbyCounts.end(), [](const auto& p1, const auto& p2) {
return p1.second > p2.second;
});
cout << "The Top 5 Hobby Metrics" << endl;
cout << "=========================" << endl;
cout << "Rank\tHobby\tCount" << endl;
cout << "=========================" << endl;
int i = 1;
for (const auto& p : hobbyCounts) {
if (i > 5) break;
cout << i++ << "\t" << p.first << "\t" << p.second << endl;
}
return 0;
}
User.h
#ifndef USER_H
#define USER_H
#include <string>
#include <vector>
class User {
public:
User(const std::string& name);
void AddHobby(const std::string& hobby);
const std::vector<std::string>& GetHobbies() const;
std::string GetName() const;
private:
std::string friendsname;
std::vector<std::string> hobbies_;
};
#endif
User.cpp
#include "User.h"
User::User(const std::string& name) {
this->friendsname = name;
}
void User::AddHobby(const std::string& hobby) {
this->hobbies_.push_back(hobby);
}
const std::vector<std::string>& User::GetHobbies() const {
return hobbies_;
}
std::string User::GetName() const {
return friendsname;
}