11

I am comparing source in a paper and I would like to put them in a table, so the differences are easily spotted. I used the following LaTeX code:

\begin{tabular}{ | l | l | l |}
Option 1  &  Option  2 & Option 3 \\
\begin{lstlisting}
Code A
\end{lstlisting} &
\begin{lstlisting}
Code B
\end{lstlisting} &
\begin{lstlisting}
Code C
\end{lstlisting} \\
\end{tabular} 

When compiled, this becomes a mess, so that is why I would like to know what I can do to improve the outcome.

ShreevatsaR
  • 45,428
  • 10
  • 117
  • 149
DigiDude
  • 113

2 Answers2

11

In addition to what said by David in his answer, you need to set breaklines=true otherwise the whole thing can become a mess if you have long lines.

For example, the following MWE (with that option set)

\documentclass{article}
\usepackage{listings}

\lstset{
  language=C,
  basicstyle=\small,
  breaklines=true
  }

\begin{document}

\noindent
\begin{tabular}{|p{3.6cm}|p{3.6cm}|p{3.6cm}|}
Option 1  &  Option  2 & Option 3 \\
\begin{lstlisting}
#include <stdio.h>

int main()
{
  printf("Hello world\n");
}
\end{lstlisting}&
\begin{lstlisting}
#include <stdio.h>

int main()
{
  printf("Hello world\n");
}
\end{lstlisting}&
\begin{lstlisting}
#include <stdio.h>

int main()
{
  printf("Hello world\n");
}
\end{lstlisting}
\end{tabular} 

\end{document} 

yields

enter image description here

while, without that option, the output is

enter image description here

karlkoeller
  • 124,410
5

l is a single line cell set to its natural width. You want each cell to be a parbox so use p{5cm} or some other suitable length, then the cell can contain display material such as a listing.

David Carlisle
  • 757,742