exercism-solutions/cpp/beer-song/beer_song.cpp

58 lines
1.2 KiB
C++

#include "beer_song.h"
#include <cctype>
#include <sstream>
namespace beer {
using namespace std;
string verse(int index)
{
auto count_str = [](int count) -> string {
if (0 == count)
return "no more bottles ";
if (1 == count)
return "1 bottle ";
ostringstream oss;
oss << count << " bottles ";
return oss.str();
};
auto capitalize_first = [](const string &str) -> string {
string result = str;
result.front() = toupper(result.front());
return result;
};
return capitalize_first(count_str(index))
+ "of beer on the wall, "
+ count_str(index)
+ "of beer.\n"
+ (index ? string("Take ")
+ (index == 1 ? "it" : "one")
+ " down and pass it around, "
: string("Go to the store and buy some more, "))
+ count_str(index ? index - 1 : 99)
+ "of beer on the wall.\n";
}
string sing(int from_index, int to_index)
{
string result;
for (int i = from_index; i >= to_index; --i) {
result += (i == from_index ? "" : "\n");
result += verse(i);
}
return result;
}
}