[Tex/LaTex] How to make lstlisting look exactly like the algorithm environment

algorithmicxlistings

I'm typesetting pseudocode with algorithm and algorithmicx to get results like the following (taken from the package documentation):
algorithm + algorithmicx

Now I would like to print real C++ code with the listings package. Is there any way to make a lstlisting look exactly the same (showing something like Listing 1 instead of Algorithm 1, of course)?

Best Answer

The caption package can be used to change the caption formatting: typeset the label in boldface font, deactivate centered captions when they fit into a single line, suppress the default label separator and replace it with a space, and add the rule before the caption. The rule after the caption and the one at the end of the caption can be added using the frame= option for \lstset; numbering and some indentations can also be controlled using features provided by the listings package:

\documentclass{article}
\usepackage{listings}
\usepackage{caption}

\lstset{
language=C++,
basicstyle=\small\ttfamily,
numbers=left,
numbersep=5pt,
xleftmargin=20pt,
frame=tb,
framexleftmargin=20pt
}

\renewcommand*\thelstnumber{\arabic{lstnumber}:}

\DeclareCaptionFormat{mylst}{\hrule#1#2#3}
\captionsetup[lstlisting]{format=mylst,labelfont=bf,singlelinecheck=off,labelsep=space}

\begin{document}

\begin{lstlisting}[caption={test algorithm}]
#include <iostream>
using namespace std;

int main()
{
  cout << "Welcome to the wonderful world of C++!!!\n";
  return 0;
}
\end{lstlisting}

\end{document}

enter image description here