Files
CSCI-1200/hws/yelp_businesses/nybusninesses.cpp
2025-02-13 14:25:47 -05:00

94 lines
3.3 KiB
C++

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <list>
#include <vector>
#include "Business.h"
int main(int argc, char* argv[]) {
if (argc < 5) {
std::cerr << "Usage: " << argv[0]
<< " input.json output.txt zipcode [categories...]"
<< std::endl;
return 1;
}
//load the arguments
std::string inputFile = argv[1];
std::string outputFile = argv[2];
std::string zipcode = argv[3];
//read all categories from arguments
std::vector<std::string> searchCategories;
for (int i = 4; i < argc; ++i) {
searchCategories.push_back(argv[i]);
}
//open the input file
std::ifstream inFile(inputFile.c_str());
if (!inFile) {
std::cerr << "Error: Could not open input file: "
<< inputFile << std::endl;
return 1;
}
//open the output file
std::ofstream outFile(outputFile.c_str());
if (!outFile) {
std::cerr << "Error: Could not open output file: "
<< outputFile << std::endl;
return 1;
}
//read each line and create a Business object if it matches the zipcode and at least one search category
std::list<Business> matchingBusinesses;
std::string line;
while (std::getline(inFile, line)) {
Business biz(line);
//check zipcode
if (biz.getPostalCode() != zipcode)
continue;
//check categories: at least one category must be found
bool categoryMatch = false;
std::string bizCategories = biz.getCategories();
for (std::vector<std::string>::const_iterator catIt = searchCategories.begin();
catIt != searchCategories.end(); ++catIt) {
if (bizCategories.find(*catIt) != std::string::npos) {
categoryMatch = true;
break;
}
}
if (categoryMatch) {
matchingBusinesses.push_back(biz);
}
}
//sort the list by rating in descending order
matchingBusinesses.sort([](const Business &a, const Business &b) {
return a.getRating() > b.getRating();
});
//output the results in a format similar to Yelp.
if (matchingBusinesses.empty()) {
outFile << "Sorry, we couldn't find any results" << std::endl;
} else {
int index = 1;
for (std::list<Business>::const_iterator it = matchingBusinesses.begin();
it != matchingBusinesses.end(); ++it) {
outFile << "=====================" << std::endl;
//add line 1: Index and Business Name
outFile << index << ". " << it->getName() << std::endl;
//add line 2: Star rating, numeric rating, and review count
outFile << it->getStarString() << " " << it->getRating()
<< " (" << it->getReviewCount() << " reviews)" << std::endl;
//add line 3: City and then the price range (if available)
outFile << it->getCity() << " ";
if (it->getPrice() != -1) {
for (int i = 0; i < it->getPrice(); ++i)
outFile << "$";
}
outFile << std::endl;
//add line 4: Categories
outFile << it->getCategories() << std::endl;
index++;
}
outFile << "=====================" << std::endl;
}
return 0;
}