36
\begin{figure}
\centerline
\begin{verbatim}
for (int a = 0; a < 10; a++)
  for (int b = 0; b < 10; b++) 
    ...
\end{verbatim}
\caption{C++ code}
\end{figure}

I would like the figure to be centered, so I include \centerline. But this induces an error. How can I fix it?

3

2 Answers 2

27

You can do this using the fancyvrb package features; in this case, the BVerbatim environment which boxes the verbatim material:

\documentclass{article}
\usepackage{fancyvrb}

\begin{document}


\begin{figure}
\centering
\begin{BVerbatim}
for (int a = 0; a < 10; a++)
  for (int b = 0; b < 10; b++) 
    ...
\end{BVerbatim}
\caption{C++ code}
\end{figure}
\noindent A\hrulefill B% just for visual guide

\end{document}

enter image description here

2
  • Could you do it without figure?
    – kravemir
    Commented Aug 31, 2015 at 17:14
  • 1
    @Miro Sure; you can use center instead of figure, suppress the \centering and use \captionof to provide the caption. I just kept the original settings of the OP. Commented Aug 31, 2015 at 19:48
12

The following solution is based on package varwidth:

\documentclass{article}
\usepackage{varwidth}

\begin{document}

\begin{figure}
\centering
\begin{varwidth}{\linewidth}
\begin{verbatim}
for (int a = 0; a < 10; a++)
  for (int b = 0; b < 10; b++)
    ...
\end{verbatim}
\end{varwidth}
\caption{C++ code}
\end{figure}

\end{document}

Result

With the help of package verbatim this can also be put in a new environment definition:

\documentclass{article}
\usepackage{varwidth}
\usepackage{verbatim}

\newenvironment{centerverbatim}{%
  \par
  \centering
  \varwidth{\linewidth}%
  \verbatim
}{%
  \endverbatim
  \endvarwidth
  \par
}

\begin{document}

\begin{figure}
\begin{centerverbatim}
for (int a = 0; a < 10; a++)
  for (int b = 0; b < 10; b++)
    ...
\end{centerverbatim}
\caption{C++ code}
\end{figure}

\end{document}

Not the answer you're looking for? Browse other questions tagged .