Here is a quick, bare-bones, example on how to price an option on a stock that pays dividend on arbitrary but known dates. For more information on QuantLib see our QuantLib pages.

Update 3 May 2023. You can try this example, in Java, in a Jupyter notebook

You can also try American option valuation with QuantLib and various supported methods using QuantLib and Python Panel here: http://quantpanel.bnikolic.co.uk/AmericanOptionEx

/**
Copyright (C) 2009, 2020 Bojan Nikolic <bojan@bnikolic.co.uk>

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE.

A bare-bones example illustrating how to price American options
with discrete dividend.

*/
#include <iostream>
#include <boost/assign/list_of.hpp>

#include <ql/quantlib.hpp>

using namespace QuantLib;

struct Inputs
{
QuantLib::Real S;
QuantLib::Real K;
QuantLib::Rate r;
QuantLib::Volatility vol;

// Dividend dates
std::vector<Date> divdates;

// Dividend ammounts
std::vector<Real> divamounts;

QuantLib::Date maturity;
QuantLib::Date settlement;
};

void setupExample(Inputs &i)
{
i.S=100;
i.K=100;
i.r=0.05;
i.vol=0.2;

i.divdates=boost::assign::list_of
(Date(1, Jan, 2009))
(Date(1, Apr, 2009))
(Date(1, Jul, 2009))
(Date(1, Oct, 2009))
;

i.divamounts=boost::assign::list_of
(1.0)
(1.0)
(1.0)
(1.0)
;

i.maturity=Date(1, Dec, 2009);
i.settlement=Date(1, Dec, 2008);

}

void Price(const Inputs &i)
{
Calendar calendar = TARGET();
Settings::instance().evaluationDate() = Date(1, Dec, 2008);
DayCounter dayCounter=Actual365Fixed();

boost::shared_ptr<Exercise>
americanExercise(new AmericanExercise(i.settlement,
i.maturity));

boost::shared_ptr<StrikedTypePayoff>
payoff(new PlainVanillaPayoff(Option::Call,
i.K ));

DividendVanillaOption opt(payoff,
americanExercise,
i.divdates,
i.divamounts);

Handle<Quote>
underlyingH(boost::shared_ptr<Quote>(new SimpleQuote(i.S)));

Handle<YieldTermStructure>
rTS(boost::shared_ptr<YieldTermStructure>(new FlatForward(i.settlement,
i.r,
dayCounter)));
Handle<BlackVolTermStructure>
flatVolTS(boost::shared_ptr<BlackVolTermStructure>(new BlackConstantVol(i.settlement,
calendar,
i.vol,
dayCounter)));

boost::shared_ptr<BlackScholesProcess>
process(new BlackScholesProcess(underlyingH,
rTS,
flatVolTS));

boost::shared_ptr<PricingEngine> pe
(new FdBlackScholesVanillaEngine(process));

opt.setPricingEngine(pe);

std::cout<<"NPV: "<<opt.NPV()
<<std::endl;

}

int main(int, char* [])
{
Inputs i;
setupExample(i);

Price(i);

}