Skip to content

Instantly share code, notes, and snippets.

@kellyegoodman
Last active August 10, 2021 16:04
Show Gist options
  • Save kellyegoodman/58d81a89e14efa21ba41d46ef122c7d0 to your computer and use it in GitHub Desktop.
Save kellyegoodman/58d81a89e14efa21ba41d46ef122c7d0 to your computer and use it in GitHub Desktop.
C++ Fizzbuzz Implementation
#include <iostream>
#include <map>
#include <string>
/* FizzBuzz prints numbers 1 through n but replaces numbers which are multiples of 3 with "Fizz",
* numbers which are multiples of 5 with "Buzz", and numbers which are multiples of both with "FizzBuzz"
*/
void FizzBuzz(int n)
{
// Map of integers to replacement strings for executing FizzBuzz
// This map can be extended from the typical FizzBuzz implementation with other <integer, string> pairs
static const std::map<int, std::string> sk_FizzBuzzMap = {{3, "Fizz"}, {5, "Buzz"}};
for (int i = 1; i <= n; ++i)
{
std::string ans;
for (auto& replacement : sk_FizzBuzzMap)
{
ans += (i % replacement.first == 0) ? replacement.second : "";
}
ans += (ans.empty()) ? std::to_string(i) : "";
std::cout << ans << std::endl;
}
}
int main(int argc, char *argv[])
{
const int defaultFizzBuzzN = 100;
// check argument list for number to FizzBuzz
if (argc < 2)
{
FizzBuzz(defaultFizzBuzzN);
}
else if (argc == 2)
{
try
{
int n = std::stoi(argv[1]);
if (n <= 0)
{
std::cerr << "N must be a positive integer greater than 0.";
return 1;
}
FizzBuzz(n);
}
catch (...)
{
std::cerr << "N must be a positive integer greater than 0.";
return 1;
}
}
else
{
std::cerr << "Only 1 argument expected: the number to FizzBuzz";
return 1;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment