Skip to content

Instantly share code, notes, and snippets.

@plusangel
Created March 1, 2020 10:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save plusangel/fead60dfffbe82ffd9cf0b3a5a07dc5b to your computer and use it in GitHub Desktop.
Save plusangel/fead60dfffbe82ffd9cf0b3a5a07dc5b to your computer and use it in GitHub Desktop.
String handling using Boost's tokenizer
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include <boost/tokenizer.hpp>
#include <iostream>
using namespace std::literals::string_literals;
int basic_calc(const std::string &input) {
boost::char_separator<char> operators{"+-*/"};
boost::tokenizer<boost::char_separator<char>> tokens{input, operators};
auto itr = tokens.begin();
auto operand1 = *itr++;
auto operand2 = *itr;
char operation = input[operand1.length()];
std::cout << "[T]" << operand1 << " " << input[operand1.length()] << " "
<< operand2 << std::endl;
int result{};
switch (operation) {
case '+':
result = stoi(operand1) + stoi(operand2);
break;
case '-':
result = stoi(operand1) - stoi(operand2);
break;
case '*':
result = stoi(operand1) * stoi(operand2);
break;
case '/':
result = stoi(operand1) / stoi(operand2);
break;
default:
std::cout << "No valid operand" << std::endl;
}
return result;
}
TEST_CASE("check calculator's functionality") {
auto str_add = "100+11"s;
auto str_sub = "100-11"s;
SECTION("add1") { REQUIRE(basic_calc(str_add) == 111); }
SECTION("sub1") { REQUIRE(basic_calc(str_sub) == 89); }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment