Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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

share|improve this question
1  
How can C code look exactly the same as pseudocode? –  egreg Sep 20 '12 at 17:04
    
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

1 Answer 1

up vote 8 down vote accepted

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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