I took all your suggestions to heart and I think it improved the code a lot.
The Map
got it's own typedef
: IntStrDict
. It's a perfectly applicable name, but I can't help but feel it's not according to best practices.
The code now accepts arguments. If no arguments are given, the code fails. If one or more argument is given it accepts the first argument as number and ignores the rest. If a non-number is inserted as first argument it should break. Recommended argument is 15016
(the result of 3*5*7*11*13
).
I'm not sure my FizzDict
in main()
is according to best practices either. I'm still looking for a way to make it more generic. Perhaps OO-style with a getFizzDict
would be appropriate. An argument which allows you to choose between dictionaries would be fancy, but could get very ugly very fast as well.
Another difference is I finally split up the code into a .cpp
and a .h
. Many functions are split up now.
Is my exception handling up to standards?
I'm trying to follow SRP as much as sensible.
FizzBuzz.cpp
#include "FizzBuzz.h"
int main(int argc, char* argv[])
{
int iMax;
try {
iMax = atoi(argv[1]);
}
catch (int e) {
std::cout << "Exception " << e << '\n';
}
if (argc < 2) {
throw 0;
}
const static IntStrDict FizzDict = {
{ 3, "Fizz" },
{ 5, "Buzz" },
{ 7, "Woof" },
{ 11, "Foo" },
{ 13, "Bar" }
};
for (int i = 1; i < iMax; ++i)
{
printString(FizzBuzzer(i, FizzDict));
}
}
FizzBuzz.h
#ifndef _fizzbuzz_h_
#define _fizzbuzz_h_
#include <iostream>
#include <string>
#include <map>
typedef std::map<int, std::string> IntStrDict;
void printString(std::string tString)
{
std::cout << tString << '\n';
}
std::string ifEmpty(int i, std::string tString)
{
if (tString.empty())
{
tString += std::to_string(i);
}
return tString;
}
std::string checkModZero(int i, IntStrDict tDict)
{
std::string tString;
for (auto const &j : tDict)
{
if (i % j.first == 0)
{
tString += j.second;
}
}
return tString;
}
std::string FizzBuzzer(int i, IntStrDict tDict)
{
std::string print;
print = checkModZero(i, tDict);
print = ifEmpty(i, print);
return print;
}
#endif // fizzbuzz