[Tex/LaTex] Fixing lstlisting inside exsheets question and solution environments

exsheetslistings

I am trying to use exsheets to prepare the tests for Foundation of Programming exam.
I need to include snippets of C code in some question and solution and I am going to use listings (with the options specified in the minimal working example below).
However I realised that the code is messed up if injected inside a question or a solution.

Do you know how to work around the problem?


Minimal Working Example

\documentclass{article}

\usepackage{xcolor}
\usepackage{listings}
\usepackage{exsheets}

\lstset{
  frame=single,
  xleftmargin=20pt,
  numbers=left,
  numberstyle=\small,
  tabsize=2,
  breaklines,
  showspaces=false,
  showstringspaces=false,
  language=C,
  basicstyle=\small\ttfamily,
  commentstyle=\itshape\color{gray}
}

\begin{document}

\begin{question}{6}
Consider the following C program.
\begin{lstlisting}
#include <stdio.h>

int main(int argc, char *argv[]) {
  printf("hello, world\n");
}
\end{lstlisting}
\end{question}

\begin{solution}
Consider the following C program.
\begin{lstlisting}
#include <stdio.h>

int main(int argc, char *argv[]) {
  printf("hello, world\n");
}
\end{lstlisting}
\end{solution}

\pagebreak
\printsolutions 

\end{document}

Best Answer

You can box your listing first, and then use the box in questions and/or solutions:

\documentclass{article}

\usepackage{xcolor}
\usepackage{listings}
\usepackage{exsheets}

\lstset{
frame=single,
xleftmargin=20pt,
numbers=left,
numberstyle=\small,
tabsize=2,
breaklines,
showspaces=false,
showstringspaces=false,
language=C,
basicstyle=\small\ttfamily,
commentstyle=\itshape\color{gray}}


\newsavebox\myboxa

\begin{document}

\begin{lrbox}{\myboxa}\begin{minipage}{\textwidth}
\begin{lstlisting}[]
#include <stdio.h>

int main(int argc, char *argv[]) {
  printf("hello, world\n");
}
\end{lstlisting}
\end{minipage}
\end{lrbox}

\begin{question}{6}
Consider the following C program.\par
\noindent\usebox\myboxa
\end{question}

\begin{solution}
Consider the following C program.\par
\noindent\usebox\myboxa
\end{solution}
\printsolutions 

\end{document}

enter image description here

Related Question