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.

3
  • 2
    Hi, welcome to TeX.SX. Your code snippet, when inserted in a minimal document, does not produce any mess. Can you expand your code to a complete, compilable example (starting with \documentclass, ending with \end{document}) that demonstrates the issue? Nov 10, 2013 at 17:59
  • 2
    If your snippets are one-liners, I would also consider \lstinline. Also, instead of a tabular, have you considered multicol? Nov 10, 2013 at 18:53
  • It's not the format you'd specifically asked for, but it may be worth using if you can live with comparing two blocks of code: diff and Is there a ready solution to typeset a diff file? or Highlighting a .diff file Nov 10, 2013 at 19:46

2 Answers 2

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

0
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.

You must log in to answer this question.

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