# Typesetting source code with listing package in Example environment

I would like to use simple example environment with listing package for printing C-code snippets, like this

\begin{example}
\lstinputlisting[caption=Hello.c]{../C/hello.c}
\end{example}


This works well with the exception of the selected font. I use

  \lstset{basicstyle=footnotesize\ttfamily}.


but, as you can see on the figure below, which does not match with selected shape. It seems that font shape selected for example environment has higher priority. How can I properly set font shape for code snippet in the example environment, that match with \lstset command.

Note: I use czech language: Příklad = Example

MNWE

\documentclass[12pt,a4paper]{scrbook}
\usepackage{amsthm}
\usepackage{xltxtra}
\usepackage{listings}

\begin{document}

\lstset{ %
language=C,                            % choose the language of the code
basicstyle=\footnotesize\ttfamily,     % the size of the fonts that are used for the code
}

\begin{example}
text text text
\begin{lstlisting}
#include <stdio.h>

int main(void)
{
int c;

while ((c = getchar()) != EOF)
putchar(c);
return 0;
}
\end{lstlisting}

\end{example}

\end{document}

• Please expand the code snippet that you have posted to a full minimal working example. A MWE should compile and be as small as possible to demonstrate your problem. – user30471 Sep 23 '16 at 7:04
• This answer might help you. – Who Save Me Save Entire World Sep 27 '16 at 12:16

The example environment from the amsthm package typesets the contents in italics. Internally, this is probably be done by calling \itshape at the beginning of the example. Now, when you create your listing, the style options \footnotesize\ttfamily are added, but the \itshape is still "active". For example:

\documentclass{article}
\begin{document}
test \itshape test \ttfamily test \upshape test
\end{document}


The same happens in your example: The surrounding text is in \itshape, thus adding \ttfamily creates text in your italic typewriter font. To get upright typewriter font, you have to add \upshape to your listings style, as demonstrated in the example above.

\documentclass[12pt,a4paper]{scrbook}
\usepackage{amsthm}
\usepackage{xltxtra}
\usepackage{listings}

\begin{document}

\lstset{ %
language=C,                                    % choose the language of the code
basicstyle=\footnotesize\upshape\ttfamily,     % the size of the fonts that are used for the code
}

\begin{example}
text text text
\begin{lstlisting}
#include <stdio.h>

int main(void)
{
int c;

while ((c = getchar()) != EOF)
putchar(c);
return 0;
}
\end{lstlisting}
text text text
\end{example}
\end{document}


and results in a listing as you would expect, with an upright typewriter font: