[Tex/LaTex] How to insert code with accents with listings

accentslistings

I'm trying to insert source code in LaTeX with using listings, but my code has accents and pdflatex gives me this error:

Unicode char \u8:�\expandafter not set up for use with LaTeX.

This is a code the reproduces the error.

example.tex

\documentclass{article}
\usepackage{listings}
\usepackage[utf8]{inputenc}
\usepackage[spanish]{babel}

\begin{document}

\lstinputlisting[language=C++]{code.cpp}

\end{document}

code.cpp

// Código con una tilde

What can I do to generate the PDF correctly?

Best Answer

You can load the package listingsutf8 and then set the encoding using \lstset{inputencoding=utf8/latin1}:

\documentclass{article}

\usepackage{listingsutf8}
\usepackage[spanish]{babel}

\begin{document}

\lstset{inputencoding=utf8/latin1}
\lstinputlisting[language=C++]{code.cpp}

\end{document}