[Tex/LaTex] How to center a listing

horizontal alignmentlistings

I'm trying to get some console output in my homework. I put it in a listings environment but I want it to be centered horizontally on the page.
The only thing I get centered is the caption ;-/

\begin{minipage}{1\textwidth}
\begin{center}
\begin{lstlisting}
a  |  b  |  q  |  u  |  s  |  v  |  t  
----------------------------------------
78 |  21 |   1 |     |   1 |   1 |  -1 
21 |  15 |   3 |   1 |  -3 |  -1 |   4 
15 |   6 |   1 |  -3 |   4 |   4 |  -5 
 6 |   3 |   2 |   4 | -11 |  -5 |  14 
 3 |     |   2 | -11 |  26 |  14 | -33 
----------------------------------------
\end{lstlisting}
\end{center}
\end{minipage}

Best Answer

I know some strange solutions involving saving the content temporary to a box and then determing the text width.

The simplest solution is to use a tabular environment:

\begin{center}
\begin{tabular}{c}
\begin{lstlisting}[...]
...
\end{lstlisting}
\end{tabular}
\end{center}

However, this doesn't center the caption. Making the caption centering correctly above the listing requires another solution. We have to take the caption out of the listings environment; this is done by a figure (or another floating environment).

Here's a way to center both your listing and the caption:

\documentclass{article}
\usepackage{listings}
\renewcommand{\figurename}{Listing}
                    % replace figurename with the text that should preceed the caption
\begin{document}

\begin{figure}[thp] % the figure provides the caption
\centering          % which should be centered
\caption{Ausgabe des C-Programms}
\begin{tabular}{c}  % the tabular makes the listing as small as possible and centers it
\begin{lstlisting}[label={gtt_c_ausgabe}]
a  |  b  |  q  |  u  |  s  |  v  |  t
----------------------------------------
78 |  21 |   1 |     |   1 |   1 |  -1
21 |  15 |   3 |   1 |  -3 |  -1 |   4
15 |   6 |   1 |  -3 |   4 |   4 |  -5
 6 |   3 |   2 |   4 | -11 |  -5 |  14
 3 |     |   2 | -11 |  26 |  14 | -33
----------------------------------------
\end{lstlisting}
\end{tabular}
\end{figure}

\end{document}