10

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)?

  • 1
    How can C code look exactly the same as pseudocode? – egreg Sep 20 '12 at 17:04
  • 1
    I refered to the design of the algorithm environment, not to the code itself, sorry :) More precisely, I would like to have the three horizontal rules, the left aligned caption and the line numbers. – ph4nt0m Sep 20 '12 at 17:09
11

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

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.