evazkj
1/7/2019 - 8:22 PM

C++ tokenizer

Bloomberg style tokenizer, error handling, file read/write

#include <bsl_iostream.h>
#include <bsl_fstream.h>
#include <bsl_sstream.h>
#include <bdlb_tokenizer.h>

namespace {

void loadStock(bsl::istream& is)
{
    using namespace BloombergLP;
    bsl::string line;
    bsl::getline(is, line);
    bdlb::Tokenizer it(line, "|");
    bsl::string ticker(it.token());
    ++it;
    bsl::stringstream ss;
    double price;
    ss << it.token();
    ss >> price;  // Use string stream for number parsing
    if (price <= 0) {
        throw bsl::runtime_error("ERROR: Negative price found");
    }
    bsl::cout << "Ticker: " << ticker << ", has price of $" << price << '\n';
}

void loadPortfolio(const char* filename)
{
    bsl::ifstream input(filename);
    if (input.is_open()) {
        while (!input.eof()) {
            try {
                loadStock(input);
            }
            catch (const bsl::runtime_error& err) {
                bsl::cerr << err.what() << '\n';
            }
        }
    }
}

}