# How to format an algorithm using lstlisting

I'm writing an algorithm using lstlisting :

 \lstset{language=C++}
\begin{lstlisting}[frame=single,caption=Algorithme de la méthode "HOG+SVM"]
HOGDescriptor hog;\\
hog.setSVMDetector(HOGDescriptor::getDefaultPeopleDetector());\\
while(1)
{
vecor<Rect> detected_persons;
hog.detectMultiScale(image,detected_persons, 0, Size(8,8), Size(32,32), 1.05, 2);
for(int i=0;i<detected_persons.size();i++)
{
rectangle(image, detected_persons[i], cv::Scalar(0,255,0),1,8,0);
}
imshow("image",image);
}
\end{lstlisting}


But I got such output this algorithm: display How to fix that?

• I think you should clarify what the expected output is and what precisely does not satisfy you in the output you are getting now. The picture you posted is not very helpful.
– GuM
Jun 9 '16 at 13:43
• listings is meant for typesetting code listings, not for algorithms itself, that's why there are packages like algorithm and algorithm2e etc. made for
– user31729
Jun 9 '16 at 13:44

The lstlisting environment does not always look nice for long lines, as you have noticed. There are alternatives (e.g., minted), but you can adjust the lstlisting output to look better.

For example, the basic size can be set to small, lines can be wrapped (and indicated as such), indentation made smaller. The following MWE has been patched together from listings: Set tabsize while using spaces for indentation in the loaded file does not work and lstlisting line wrapping and manually removing the top-level indentation.

\documentclass{article}
\usepackage{amsmath}
\usepackage{xcolor}
\usepackage{listings}
\lstset{
language=C++,
basicstyle=\small,       % font size
breaklines=true,         % line wrap
postbreak=\raisebox{0ex}[0ex][0ex]{\ensuremath{\color{red}\hookrightarrow\space}},        % arrow on wrapped lines
literate={\ \ }{{\ }}1   % adjust tab size
}
\begin{document}
\begin{lstlisting}[frame=single,caption=Algorithme de la m\'{e}thode "HOG+SVM"]
HOGDescriptor hog;
hog.setSVMDetector(HOGDescriptor::getDefaultPeopleDetector());
while(1)
{